C if...else Statement
An if statement can be followed by an optional else statement, which executes when the Boolean expression is false.
Syntax
The syntax for an if...else statement in C language is:
if(boolean_expression)
{
/* Statements to execute if the Boolean expression is true */
}
else
{
/* Statements to execute if the Boolean expression is false */
}
If the Boolean expression is true, the code inside the if block is executed. If the Boolean expression is false, the code inside the else block is executed.
C language considers any non-zero and non-null values as true, and zero or null as false.
Flowchart
Example
Example
#include <stdio.h>
int main ()
{
/* Local variable definition */
int a = 100;
/* Check the boolean condition */
if( a < 20 )
{
/* If condition is true then print the following */
printf("a is less than 20\n" );
}
else
{
/* If condition is false then print the following */
printf("a is greater than 20\n" );
}
printf("The value of a is %d\n", a);
return 0;
}
When the above code is compiled and executed, it produces the following result:
a is greater than 20
The value of a is 100
if...else if...else Statement
An if statement can be followed by an optional else if...else statement, which is useful to test various conditions.
When using if...else if...else statements, the following points should be kept in mind:
An if can be followed by zero or one else, which must be after any else if.
An if can be followed by zero or more else if, which must be before the else.
Once an else if matches successfully, none of the remaining else if or else will be tested.
Syntax
The syntax for an if...else if...else statement in C language is:
if(boolean_expression 1)
{
/* Executes when the Boolean expression 1 is true */
}
else if( boolean_expression 2)
{
/* Executes when the Boolean expression 2 is true */
}
else if( boolean_expression 3)
{
/* Executes when the Boolean expression 3 is true */
}
else
{
/* Executes when none of the above conditions are true */
}
Example
Example
#include <stdio.h>
int main ()
{
/* Local variable definition */
int a = 100;
/* Check the boolean condition */
if( a == 10 )
{
/* If the condition is true then print the following */
printf("The value of a is 10\n" );
}
else if( a == 20 )
{
/* If the else if condition is true */
printf("The value of a is 20\n" );
}
else if( a == 30 )
{
/* If the else if condition is true */
printf("The value of a is 30\n" );
}
else
{
/* If none of the conditions is true */
printf("No matching value found\n" );
}
printf("The exact value of a is %d\n", a );
return 0;
}
When the above code is compiled and executed, it produces the following result:
No matching value found
The exact value of a is 100