'if' Conditional Statement
In C, the 'if' conditional statement is used for conditional execution of a block of code. The code will be executed if the condition is true.
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' condition
Simple syntax of 'if' condition is demonstrated in the following example:
xxxxxxxxxx
if (condition) {
// block of code to be executed if condition is true
}
-
if (condition)
: In the line, 'if' is followed by a condition placed inside parentheses '()'. - The block of code to be executed is placed inside curly braces '{}'. The code will be executed if the condition is true.
Create an 'if' conditional statement
An 'if' conditional statement has been created in the following example:
Example of 'if' conditional statement
xxxxxxxxxx
#include <stdio.h>
int main() {
if (10 > 5) {
printf("10 is greater than 5.");
}
return 0;
}
Output of the above example
10 is greater than 5.
Explanation of code:
-
if (10 > 5)
: The line declares an 'if' conditional statement where the condition is '10 > 5'. We know that the condition is true as 10 is greater than 5. -
printf("10 is greater than 5.");
is the block of code which will be executed if the condition of 'if' is true. In this case, the code block will be executed as the 'if' condition is true.
'if' conditional statement with multiple conditions
An 'if' conditional statement with multiple conditions has been created in the following example:
Examples of 'if' conditional statement with multiple conditions
xxxxxxxxxx
#include <stdio.h>
int main() {
if (10 > 5 && 9 < 12) {
printf("10 is greater than 5 and 9 is smaller than 12.");
}
return 0;
}
Output of the above example
10 is greater than 5 and 9 is smaller than 12.
Explanation of code:
-
if (10 > 5 && 9 < 12)
: The line declares an 'if' conditional statement with two conditions '10 > 5' and '9 < 12' joined by logical AND (&&). We know that the both conditions are true. -
printf("10 is greater than 5 and 9 is smaller than 12.");
is the code block which will be executed as the condition of 'if' is true. In this case, the code block will be executed as the 'if' condition is true.