If-else statement is a type of conditional statement that allows the program to execute one block of code if a certain condition is true and an else block of code is executed if the condition is false. It contains two blocks of code and depending on the condition any one of the blocks is getting executed.
Syntax:
if (condition) {
// this block of code is executed if condition is true
} else {
// this block of code is executed if condition is false
}Here,
if: keyword used to initiate the conditional statement.
(condition): to check the condition it can be any expression that evaluates to a boolean value (true or false).
{ }: enclose the block of code to be executed if the condition is true.
else: keyword used to execute the block of statement if condition fails.
{ }: enclose the block of code to be executed if the condition is false.
Below is the Solidity program to implement the if-else statement:
// Solidity program to implement // if-else statement pragma solidity ^0.8.15; // Declaring contract contract Example {
// Declaring one variable
uint public value;
// Declaring function with argument
function setValue(uint newValue) public {
// if value is greater than 10
// value will be assigned as newValue
if (newValue > 10)
{
value = newValue;
// else value will be zero.
} else
{
value = 0;
}
}
} |
Explanation: In this example, a contract called “Example” is declared that has one variable called “value”.
- The function “setValue” is declared as public, which means it can be called by anyone.
- Inside the “setValue” function, an “if-else” statement is used to check whether the value passed as an argument to the function is greater than 10.
- If it is, we set the value of the “value” variable to the new value that was passed as an argument.
- If the value passed as an argument is not greater than 10, then the “else” block of code will execute and set the value of “value” to 0.
Output:
Case 1: If block is executed
value = 12 (greater than 10) so the newValue = 12.
Case 2: Else block is executed
value = 8 (less than 10) so the newValue = 0.