You are on page 1of 12

CSI 124

Structured Programming Language

Lecture 03
if else
Control or decision making statement
• if statement
– The if statement evaluates the expression inside
the parenthesis.
– If the expression is true (nonzero), statements
inside the body of if is executed.
– If the test expression is false (0), statements inside
the body of if is skipped from execution.
if (Expression)
{
// statements
}
Flowchart of if statement
The if statement
#include <stdio.h>
main(){
int a,b;
printf("take two inputs:");
scanf("%d %d",&a,&b);
if(a>b)
{
printf(“%d is greater“,a);
}
printf(“end of program”);
}
The if else statement
• if (Expression)
{
// codes inside the body of if
}
else {
// codes inside the body of else
}
• If expression is true, codes inside the body of if
statement is executed and, codes inside the body of
else statement is skipped.
• If expression is false, codes inside the body of else
statement is executed and, codes inside the body of
if statement is skipped.
Flowchart of if...else statement
The if else statement
#include <stdio.h>
main(){
int a,b;
printf("take two inputs:");
scanf("%d %d",&a,&b);
if(a>b)
{
printf(“%d is greater“,a);
}
else
{
printf(“%d is greater“,b);
}
printf(“end of program”);
}
Nesting of if else statement
• When an if statement appears inside the other
it is called nesting of if statements.
• Nesting of if statements is very helpful when
you have something to do by following more
than one decision.
Nesting of if else statement
void main(){
int a,b,c;
printf("take three nmbers:");
scanf("%d%d%d",&a,&b,&c);
if(a>b)
{
if(a>c)
{printf("%d is greater",a);}
else
{printf("%d is greater",c);}
}
else
{
if(b>c)
{printf("%d is greater");}
else
{printf("%d is greater",c);}

}
}
The else if ladder

• A ladder of if-else conditions will be evaluated


from top to down.
• As soon as an if statement from the ladder
evaluates to true, the statements associated
with that if are executed, and the remaining
part of the ladder is bypassed.
• The last most else is executed only when no
condition in the whole ladder returns true.
The else if ladder
#include<stdio.h>
void main(){
int grade;
printf("Enter your grade: ");
scanf("%d",&grade);
if (grade>90)
printf("Grade: A");
else if (grade>80)
printf("Grade: B");
else if (grade>70)
printf("Grade: C");
else if (grade>60)
printf("Grade: D");
else if (grade>50)
printf("Grade: E");
else
printf("Grade: F");
}
Thanks for your time and attention.

You might also like