If Statements
All the statements in the c program are executed sequentially (a) each statement, but this if statement moves the program execution from one place to another.
When the if statement is executed, the first condition is checked. If the condition is true, then the single statement (or) group of statement that comes after it will be executed. If the condition is false, the next statement will be executed.
Syntax
if(condition)
{
statements;
}
Ex:
#include<stdio.h>
#include<conio.h>
void main()
{
int age;
printf("Enter your AGE");
scanf("%d",&age);
if(age>18)
{
printf("\n Eligible for the exam");
}
printf("Not Eligible for the exam");
getch();
}
OUTPUT 1:
Enter your AGE: 19
Eligible for the exam
OUTPUT 2:
Enter the AGE:10
Not Eligible for the exam
if…else
When the condition is checked, if it is true, a group of statement is executed. If it is false, another group of statement is executed.
syntax:
if(condition)
{
statement 1;
statement 2;
.
.
.
true block;
.
.
.
statement n;
}
else
{
statement 1;
statement 2;
.
.
.
.
false block;
.
.
.
statement n;
}
Programme:
#include<stdio.h>
#include<conio.h>
void main()
{
int mark;
printf("Enter your MARK");
scanf("%d",&mark);
if(mark>35)
{
printf("\n PASS");
}
else
{
printf("\n FAIL");
}
getch();
}
OUTPUT 1:
Enter your MARK:30
FAIL
OUTPUT 2:
Enter the MARK:50
PASS
If..else if
First, when the condition in the if is checked, if the condition is true, the group of statement in the if block will be executed. If not, then the condition in the else if will be checked. If the condition is true, the group of statement in the else if will be executed. .If all the conditions are false then the statement in the else block will be executed.
syntax:
if(condition)
{
statements;
}
elseif(condition)
{
statements;
}
else(condition)
{
statements;
}
#include<stdio.h>
#include<conio.h>
void main()
{
int day;
printf("Enter a number between 1 and 7");
scanf("%d",&day);
if(day==1)
{
printf("\n MONDAY");
}
elseif(day==2)
{
printf("\n TUESDAY");
}
elseif(day==3)
{
printf("\n WEDNESDAY");
}
elseif(day==4)
{
printf("\n THURSDAY");
}
elseif(day==5)
{
printf("\n FRIDAY");
}
elseif(day==6)
{
printf("\n SATURDAY");
}
elseif(day==7)
{
printf("\n SUNDAY");
}
else
{
printf("\nplease....give a number between 1 to 7");
}
getch();
}
OUTPUT 1:
Enter a number between 1 and 7:1
MONDAY
OUTPUT 2:
Enter a number between 1 and 7:8
please....give a number between 1 to 7
Nested if…else statement:
If (or) else statement comes again inside the if (or) else block, it is called nested if ...else statement.
syntax:
if(condition 1)
{
if(condition 2)
{
statements;
}
else
{
statements;
}
}
else
{
statements;
}
Programme:
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,c;
printf("Enter three numbers:");
scanf("%d %d %d",&a,&b,&c);
if(a>b)
{
if(a>c)
{
printf("\n Big=%d",a);
}
else
{
printf("\n Big=%d",c);
}
}
else
{
if(b>c)
{
printf("\n Big=%d",b);
}
else
{
printf("\n Big=%d",c);
}
}
}
OUTPUT:
Enter three numbers: 7 6 8
Big = 8