Conditional statements helps you to make decision based on certain conditions. These conditions are specified by a set of conditional statements having boolean expressions which are evaluated to a boolean value true or false. There are following types of conditional statements in C.
If statement
If-Else statement
If-Else If ladder
Nested If-else statement
Switch statement
The single if statement in C language is used to execute the code if condition is true.
if(expression)
{
//code to be executed
}
#include<stdio.h>
#include<conio.h>
void main()
{
int num=0;
printf("enter the number");
scanf("%d",#);
if(n%2==0)
{
printf("%d number in even",num);
}
getch();
}
The if-else statement in C language is used to execute the code if condition is true or false.
if(expression)
{
//Statements
}
else
{
//Statements
}
#include<stdio.h>
#include<conio.h>
void main()
{
int num=0;
printf("enter the number");
scanf("%d",#);
if(n%2==0)
{
printf("%d number in even", num);
}
else
{
printf("%d number in odd",num);
}
getch();
}
The if else-if statement is used to execute one code from multiple conditions.
if(condition1)
{
//statements
}
else if(condition2)
{
//statements
}
else if(condition3)
{
//statements
}
else
{
//statements
}
#include<stdio.h>
#include<conio.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");
}
getch();
}
The nested if...else statement is used when program requires more than one test expression.
if( expression )
{
if( expression1 )
{
statement-block1;
}
else
{
statement-block 2;
}
}
else
{
statement-block 3;
}
#include<stdio.h>
#include<conio.h>
void main( )
{
int a,b,c;
clrscr();
printf("Please Enter 3 number");
scanf("%d%d%d",&a;,&b;,&c;);
if(a>b)
{
if(a>c)
{
printf("a is greatest");
}
else
{
printf("c is greatest");
}
}
else
{
if(b>c)
{
printf("b is greatest");
}
else
{
printf("c is greatest");
}
}
getch();
}