else if ladder
The general form of else-if ladder is,if(expression1)
{
statement block1;
}
else if(expression2)
{
statement block2;
}
else if(expression3 )
{
statement block3;
}
else
default statement;
The expression is tested from the top(of the ladder) downwards.
As soon as a true condition is found,
the statement associated with it is executed.
#include <stdio.h>
void main( )
{
int a;
printf("Enter a number...");
scanf("%d", &a);
if(a%5 == 0 && a%8 == 0)
{
printf("Divisible by both 5 and 8");
}
else if(a%8 == 0)
{
printf("Divisible by 8");
}
else if(a%5 == 0)
{
printf("Divisible by 5");
}
else
{
printf("Divisible by none");
}
}
Points to Remember
In if statement, a single statement can be included without enclosing it into curly braces { ... }int a = 5;
if(a > 4)
printf("success");
No curly braces are required in the above case,
but if we have more than one statement inside if condition,
then we must enclose them inside curly braces.
== must be used for comparison in the expression of if condition,
if you use = the expression will always return true,
because it performs assignment not comparison.
Other than 0(zero), all other values are considered as true
if(27)
printf("hello");