'if...else' Conditional Statement
In C, the 'if...else' conditional statement is used for conditional execution of a block of code out of two alternative blocks of code.
If the 'if' condition is true, the code block under 'if' condition will be executed. If the 'if' condition is false, the code block under 'else' condition will be executed.
The condition in an if statement is evaluated in a boolean context (either 'True' or 'False').
These comparison operators ('==', '!=', '<', '>', '<=', '>='
) and logical operators ('&&', '||', '!'
) are commonly used for comparison in the if condition.
Syntax of 'if...else' condition
Simple syntax of 'if...else' condition is demonstrated in the following example:
xxxxxxxxxx
if (condition) {
// Code of if block to be executed if the condition is true
} else {
// Code of else block to be executed if the condition is false
}
-
if (condition)
: In the line, 'if' is followed by a condition inside parentheses '()'. - The code of if block is placed inside curly braces '{}' under if condition. The code will be executed if the condition is true.
-
else
: 'else' is used to execute the code under 'else' block if the 'if' condition is false. - The code of else block is placed inside curly braces '{}' under 'else' statement. The code will be executed if the 'if' condition is false.
Create an 'if...else' conditional statement
An 'if...else' conditional statement has been created in the following example:
Example of 'if...else' conditional statement
xxxxxxxxxx
#include <stdio.h>
int main() {
if (5 > 10) {
printf("10 is greater than 5.");
}
else {
printf("5 is less than 10.");
}
return 0;
}
Output of the above example
5 is less than 10.
Explanation of code:
-
if (5 > 10)
: The line declares an 'if' conditional statement where the condition is '5 > 10'. We know that the condition is false as 5 is not greater than 10. -
printf("10 is greater than 5.");
: The line is the code block under 'if' statement. In this case, this code block will not be executed as the 'if' condition is false. -
else
is used to execute a block of code if the condition of 'if' statement is false. In this case, the 'else' code block will be executed as the condition is false. -
printf("5 is less than 10.");
: The line is the code block under 'else' statement. In this case, this code block will be executed as the 'if' condition is false.