Please enable Javascript to correctly display the contents on Dot Net Tricks!

Conditional Statements

Posted On : 13 Dec 2015
Updated On : 22 Dec 2015
Total Views : 759

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.

  1. If statement

  2. If-Else statement

  3. If-Else If ladder

  4. Nested If-else statement

  5. Switch statement

If statement

The single if statement in C language is used to execute the code if condition is true.

Syntax

if(expression)
{
 //code to be executed
}

Example

#include<stdio.h>
#include<conio.h>
void main()
{
int num=0;
printf("enter the number");
scanf("%d",&num);
if(n%2==0)
{
printf("%d number in even",num);
}
getch();
}

If-else statement

The if-else statement in C language is used to execute the code if condition is true or false.

Syntax

if(expression)
{
 //Statements
}
else
{
 //Statements
}

Example

#include<stdio.h>
#include<conio.h>
void main()
{
int num=0;
printf("enter the number");
scanf("%d",&num);
if(n%2==0)
{
printf("%d number in even", num);
}
else
{
printf("%d number in odd",num);
}
getch();
}

If-else If ladder

The if else-if statement is used to execute one code from multiple conditions.

Syntax

if(condition1)
{
 //statements
} 
else if(condition2)
{
 //statements
}
else if(condition3)
{
 //statements
}
else
{
 //statements
}

Example

#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();
}

Nested If-else statement

The nested if...else statement is used when program requires more than one test expression.

Syntax

if( expression )
{ 
 if( expression1 )
 {
 statement-block1;
 }
 else 
 {
 statement-block 2;
 }
}
else
{
 statement-block 3;
}

Example

#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();
}