Conditional_Statements
Conditional_Statements
Syntax:
Syntax: if (condition)
{ // code to execute }
Example:
1|Page
Explanation:
Syntax:
if (condition) {
// code to execute if condition is true
}
else {
// code to execute if condition is false
}
Example 1:
2|Page
This example checks if the age is 18 or above. If true, it grants voting rights;
otherwise, it denies them.
Example 2:
Explanation:
3|Page
Syntax :
if (condition1) {
// code to execute if condition 1 is true
} else if
(condition2) {
// code to execute if condition 2 is true
}
else {
// code to execute if both condition1 and condition2 are
false
}
This code first checks if the user is 18 or older. If true, it then checks their
citizenship status. Only if both conditions are met are voting rights granted.
// Ticket Pricing
uint256 age = 25;
uint256 ticketPrice;
4|Page
if (age <= 5) {
ticketPrice = 0; // Free for children under 5
} else if (age <= 12) {
ticketPrice = 10; // Child ticket price
} else if (age <= 65) {
ticketPrice = 20; // Adult ticket price
} else {
ticketPrice = 15; // Senior citizen discount
}
This example calculates the ticket price based on age categories using
if..else..if statements.
5|Page