if else if ladder statement in c language | ladder if statement in C
It is basically a multi way decision making statement. In if else if ladder statement, there are multiple conditions one after another. Depending upon these conditions, specific sets of statements are executed.
The syntax of if else if ladder statement is:
if(TestCondition-1)
{
Block-1;
}
else if(TestCondition-2)
{
Block-2;
}
else if (TestCondition-3)
{
Block-3;
}
:
:
else
{
Block-N;
}
TestCondition-1, TestCondition-2 and TestCondition-3 are conditions made using relational or logical operators.
Initially TestCondition-1 is checked. If it is true, Block-1 of statements will get executed. If TestCondition-1 is false, TestCondition-2 is checked. If TestCondition-2 is true Block2 of statements gets executed. If TestCondition-2 is false, TestCondition-3 will be checked. If TestCondition-3 is true Block3 of statements gets executed.
Block-N will be executed if all conditions are false.
Block-1, Block-2, Block-3 and Block-N are set of statements, which will be executed depending upon various Conditions. These blocks of statements must contain valid statements of C language.
Program to demonstrate the use of if else if ladder statement in C. |
#include<stdio.h> int main() { int a; printf("\nEnter a number :="); scanf("%d",&a); if(a>0) printf("\nValue is positive"); else if(a<0) printf("\nValue is negative"); else printf("\nValue is zero"); return 0; } |
Output |
Enter a value :=-5 Value is negative |
In the above program, a has been entered 6. Condition if(a>0) is true, printf(“\nValue is positive”) would be executed.