You are on page 1of 19

Control-Flow statements-I

6
(Conditional control-flow statements)

Chapter Outline
“I can't change the direction of the wind, but I
can adjust my sails to always reach my Introduction.
destination.” –Jimmy Dean
Conditional control-flow
statements.
if statement.
simple if statement.
if else statement.
nested if else statement.
“Men, like nails, lose their usefulness when they
else if ladder.
lose direction and begin to bend.”
–Walter Savage Landor switch statement
Conclusion.

“The means to gain happiness is to throw out from


oneself like a spider in all directions an adhesive
web of love, and to catch in it all that comes”
-Leo Nikolaevich Tolstoy
6.1. Introduction
Simple statement: A simple statement is a syntactic construct that is used for performing a specific task.
Usually, a simple statement is terminated with a semi-colon (;).
Ex: c=a+b; //An assignment statement
a+b=c; // Not a statement; syntactically it is wrong
printf(“\n Hello world!”); //An output statement

Compound statement (or) Block: A compound statement is a collection of one or more simple
statements that are enclosed with in curly braces { and }. A block can be treated logically as one
statement. The statements in a block are executed sequentially.
Ex: {
int a=10,b=20;
c=a+b;
printf(“%d”,c);
}
Note: 1) A block can be placed in another block.
2) Forgetting the placing of one of the curly braces leads to syntax or logical error.

Null statement (or) Empty statement (or) void statement: A null statement is a statement that
serves for nothing. But, it is executed as a normal statement. A null statement is denoted as ;. A null
statement can appear wherever a statement is expected. Its use is necessary in cases where the presence
of a statement is required by the syntax, but no action is logically needed.

Control-Flow statement: Control-flow statement is a statement that determines the flow of control
during execution of a program. Flow of control is the order of execution of statements with in a program.
There are 3 kinds of control-flow statements:

Control-flow Statements

Conditional Looping Jumping


Control-flow Control-flow Control-flow
Statements Statements Statements

 if statement  while statement  break statement


 switch statement  do…while statement  continue statement
 for statement  goto statement
6.2. Conditional control-flow statements
Conditional control-statements are the control-flow statements that determine the flow of control based on
the condition. These are also called as decision-making control-flow statements or selection control-flow
statements. As the name implies, these are used to make a decision based on the available choices.
Decision making in a program is concerned with choosing or selecting to execute one set of statements
rather than another.
There are two conditional control-flow statements:
1. if statement
2. switch statement

6.2.1. if statement
if statement is one of decision-making control-flow statements. It has 4 notations:
1. Simple if statement.
2. if…else statement.
3. Nested if…else statement.
4. else if ladder
6.2.1.1. Simple if statement
Simple if statement is used to make a decision based on the available choice. It has the following form:

if(<condition>)
if-body
next-statement

In this syntax,
 If is the keyword. <condition> is a relational expression or logical expression or any expression
that returns either true or false. It is important to note that the condition should be enclosed within
parentheses ( and ).
 The if-body can be a simple statement or a compound statement or a null statement.
 Next-statement is any valid C statement.
Whenever simple if statement is encountered, first the condition is tested. It returns either true or
false. If the condition is false, the control transfers directly to next-statement with out considering the if-
body. If the condition is true, the control enters into the if-body. Once, the end of if-body is reached, the
control transfers to next-statement. The flow of control using simple if is determined as follows:
Program #1
Write a program to calculate salary of an employee based on the following condition:
If he served the organization for more than 15 years, add Rs1500.00 to his basic salary.
/* A program to calculate employee’s salary*/
#include<stdio.h>
main()
{
float salary,bonus;
int yoj,cy,yos;
printf(“\n Enter current year and year of joining:”);
scanf(“%d%d”,&cy,&yoj);
printf(“\n Enter employee’s basic salary:”);
scanf(“%f”,&salary);
bonus=0;
yos=cy-yoj;
if(yos>=15)
bonus=1500; //if-body
salary=salary+bonus;
printf(“\n Salary=Rs. %.2f”,salary);
}
Run:
Enter current year and year of joining :2010 1992
Enter employee’s basic salary: 10000
Salary=Rs. 11500.00

Program #2
Write a program to calculate salary of an employee based on the following condition:
If he served the organization for more than 15 years:
Calculate 25% of his salary as HRA
Calculate 10% of his salary as DA
Rs1500.00 as bonus to his basic salary.
/* A program to calculate employee’s salary*/
#include<stdio.h>
main()
{
float salary,bonus,HRA,DA;
int yoj,cy,yos;
printf(“\n Enter current year and year of joining:”);
scanf(“%d%d”,&cy,&yoj);
printf(“\n Enter employee’s basic salary:”);
scanf(“%f”,&salary);
yos=cy-yoj;
if(yos>=15)
{ //if-body
HRA=(salary*25)/100.00;
DA=(salary*10)/100.00;
bonus=1500;
}
salary=salary+bonus+HRA+DA;
printf(“\n Salary=Rs. %.2f”,salary);
}
Run:
Enter current year and year of joining :2010 1992
Enter employee’s basic salary: 10000
Salary=Rs. 15000.00
6.2.1.2. if…else statement
if…else statement is used to make a decision based on two choices. It has the following form:

if(<condition>)
if-body
else
else-body
next-statement

In this syntax,
 If and else are the keywords.
 <condition> is a relational expression or logical expression or any expression that returns either true
or false. It is important to note that the condition should be enclosed within parentheses ( and ).
 The if-body and else-body are simple statements or compound statements or null statements.
 Next-statement is any valid C statement.
Whenever if...else statement is encountered, first the condition is tested. It returns either true
or false. If the condition is true, the control enters into the if-body. Once, the end of if-body is reached,
the control transfers to next-statement without considering else-body.
If the condition is false, the control enters into the else-body by skipping if-body. Once, the end
of else-body is reached, the control transfers to next-statement. The flow of control using if...else
statement is determined as follows:

Note: if…else statement behaves same as the conditional operator ( ? : ) works.


Ex: if(n%2==0)
printf(“\nEVEN”); is same as (n%2==0)?printf(“\n EVEN”):printf(“\n ODD”);
else
printf(“\n ODD”);
Program #3
Write a program to check whether given year is leap year or not
/* A program to check whether given year is leap year or not*/
#include<stdio.h>
main()
{
int year;
printf(“\n Enter any year:”);
scanf(“%d”,&year);
if((year%4==0&&year%100!=0)||(year%400==0)
printf(“\n Given year is a leap year”);
else
printf(“\n Given year is not a leap year”);
}
Run:
Enter any year: 2000
Given year is a leap year

Program #4
Write a program to calculate salary of an employee based on the following conditions:
If he served the organization for more than 15 years:
Calculate 25% of his salary as HRA
Calculate 10% of his salary as DA
Rs1500.00 as bonus to his basic salary.
Otherwise:
Calculate 15% of his salary as HRA
Calculate 5% of his salary as DA
/* A program to calculate employee’s salary*/
#include<stdio.h>
main()
{
float salary,bonus,HRA,DA;
int yoj,cy,yos;
printf(“\n Enter current year and year of joining:”);
scanf(“%d%d”,&cy,&yoj);
printf(“\n Enter employee’s basic salary:”);
scanf(“%f”,&salary);
yos=cy-yoj;
if(yos>=15)
{ //if-body
HRA=(salary*25)/100.00;
DA=(salary*10)/100.00;
bonus=1500;
}
else
{
HRA=(salary*15)/100.00;
DA=(salary*5)/100.00;
bonus=0;
}
salary=salary+bonus+HRA+DA;
printf(“\n Salary=Rs. %.2f”,salary);
}
6.2.1.3. Nested if…else statement
Nested if…else statement is one of the conditional control-flow statements. If the body of if statement
contains at least one if statement, then that if statement is called as “Nested if…else statement”. The
nested if…else statement can be used in such a situation where at least two conditions should be satisfied
in order to execute particular set of instructions. It can also be used to make a decision among multiple
choices. The nested if…else statement has the following form:

if(<condition1>)
if(<condition2>)
if-body
else
else-body
next-statement

In this syntax,
 if and else are keywords.
 <condition1>,<condition2> … <condition> are relational expressions or logical expressions or any
other expressions that return true or false. It is important to note that the condition should be
enclosed within parentheses ( and ).
 If-body and else-body are simple statements or compound statements or empty statements.
 Next-statement is a valid C statement.
Whenever nested if…else statement is encountered, first <condition1> is tested. It returns
either true or false.
If condition1 (or outer condition) is false, then the control transfers to else-body (if exists) by
skipping if-body.
If condition1 (or outer condition) is true, then condition2 (or inner condition) is tested. If the
condition2 is true, if-body gets executed. Otherwise, the else-body that is inside of if statement gets
executed.
Interview question #1
What is dangling else problem?
Dangling else problem is an ambiguous situation in which one can not judge the else statement to
which if statement it belongs to. E.g., in the above syntax, we can not judge the else statement
whether it belongs to outer if statement or inner if statement.
In order to solve this problem, it is better to include the outer-if-body in curly braces. Hence, the
above syntax can be redefined as:
if(<condition1>) if(<condition1>)
{ {
if(<condition2>) if(<condition2>)
if-body if-body
} else //inner else
else //outer else else-body
else-body }
next-statement else
else-body
next-statement
The flow of control using nested if…else statement is determined as follows:

Program #5
Write a program to find biggest of three numbers
/* A program to find biggest, sum and average of three numbers*/
#include<stdio.h> #include<stdio.h>
main() main()
{ {
int a,b,c,big,sum; int a,b,c,big,sum;
float avg; float avg;
printf(“\n Enter any three numbers:”); printf(“\n Enter any three numbers:”);
scanf(“%d%d%d”,&a,&b,&c); scanf(“%d%d%d”,&a,&b,&c);
if(a>b) if(a>b && a>c)
{ big=a;
if(a>c) if(b>a && b>c)
big=a; big=b;
} if(c>a && c>b)
else big=c;
{ sum=a+b+c;
if(b>c) avg=sum/3.0;
big=b; printf(“\n Biggest number=%d”,big);
else printf(“\n Sum=%d”,sum);
big=c; printf(“\n Average=%f”,avg);
} }
sum=a+b+c;
avg=sum/3.0;
printf(“\n Biggest number=%d”,big);
printf(“\n Sum=%d”,sum);
printf(“\n Average=%f”,avg);
}

Run:
Enter any three numbers: 34 54 23
Biggest number=54
Program #6
Write a program to print eligibility for voting
/* A program to print eligibility for voting*/
#include<stdio.h>
main()
{
int age;
char sex;
printf(“\n Enter age and sex:”);
scanf(“%d\n%c”,&age,&sex);
if(sex==’m’||sex==’M’||sex==’f’||sex==’F’)
{
if(age>=18)
printf(“\n You are eligible for voting”);
else
printf(“\n Sorry, you are not eligible for voting”);
}
else
printf(“\n You are eligible for special type of voting”);

}
Run:
Enter age and sex:
23
K
You are eligible for special type of voting

6.2.1.4. else if ladder


Else if ladder is one of the conditional control-flow statements. It is used to make a decision among
multiple choices. It has the following form:
if(<condition1>)
if-body
else if(<condition2>)
else-if-body1
else if(<condition3>)
else-if-body2
else if(<condition4>)
else-if-body3
:
:
else if(<conditionN>)
else-if-bodyN
else
else-body
Next-statement

In this syntax,
 if and else are keywords. There should be a space between else and if, if they come together.
 <condition1>,<condition2>….<condtionN> are relational expressions or logical expressions or any
other expressions that return either true or false. It is important to note that the condition should
be enclosed within parentheses ( and ).
 If-body, else-if-body1,else-if-body2….else-if-bodyN, and else-body are either simple statements or
compound statements or null statements.
 Next-statement is a valid C statement.
Whenever else if ladder is encountered, condition1 is tested first. If it is true, the if-body gets
executed. After then the control transfers to next-statement.
If condition1 is false, then condition2 is tested. If condition2 is false, the other conditions are
tested. If all are false, the else-body at the end gets executed. After then the control transfers to next-
statement.
If any one of all conditions is true, then the body associated with it gets executed. After then
the control transfers to next-statement.
The flow control using else if ladder is determined as follows:
Program #7
Write a program to find biggest of 6 numbers
/* A program to find biggest of 6 numbers*/
#include<stdio.h>
main()
{
int a,b,c,d,e,f,big;
printf(“\n Enter any 6 numbers:”);
scanf(“%d%d%d%d%d%d”,&a,&b,&c,&d,&e,&f);
if(a>b && a>c && a>d && a>e && a>f)
big=a;
else if(b>c && b>d && b>e && b>f)
big=b;
else if(c>d && c>e && c>f)
big=c;
else if(d>e && d>f)
big=d;
else if(e>f)
big=e;
else
big=f;
printf(“\n Biggest number=%d”,big);
}
Run:
Enter any 6 numbers: 23 54 2 435 32 87
Biggest number=435

Program #8
Write a program to print the type of character that is being input
/* A program to print the type of character that is being input*/
#include<stdio.h>
main()
{
char ch;
printf(“\n Enter any character:”);
scanf(“\n%c”,&ch);
if(ch>=’A’ &&ch<=’Z’)
printf(“\n You entered Upper case alphabet”);
else if(ch>=’a’ && ch<=’z’)
printf(“\n You entered lower case alphabet”);
else if(ch>=’0’ && ch<=’9’)
printf(“\n You entered a digit”);
else if(ch==’ ’ || ch==’\n’ || ch==’\t’)
printf(“\n You entered a white space character”);
else
printf(“\n You entered a special symbol”);
}
Run:
Enter any character:
*
You entered a special symbol
6.2.2. switch statement
switch statement is one of decision-making control-flow statements. Just like else if ladder, it is also used
to make a decision among multiple choices. switch statement has the following form:

switch(<exp>)
{
case <exp-val-1>: statements block-1
break;
case <exp-val-2>: statements block-2
break;
case <exp-val-3>: statements block-3
break;
:
:
case <exp-val-N>: statements block-N
break;
default: default statements block
}
Next-statement

In this syntax,
 switch, case, default and break are keywords.
 <exp> is any expression that should give an integer value or character value. In other words, it
should never return any floating-point value. It should always be enclosed with in parentheses
( and ). It should also be placed after the keyword switch.
 <exp-val-1>, <exp-val-2>, <exp-val-3>…. <exp-val-N> should always be integer constants or
character constants or constant expressions. In other words, variables can never be used as <exp-
val>. There should be a space between the keyword case and <exp-val>. The keyword case along
with its <exp-val> is called as a case label. <exp-val> should always be unique; no duplications
are allowed.
 Statements block-1, statements-block-2, statements block-3… statements block-N and default
statements block are simple statements, compound statements or null statements. It is important
to note that the statements blocks along with their own case labels should be separated with a
colon ( : ).
 The break statement at the end of each statements block is an optional one. It is recommended
that break statement always be placed at the end of each statements block. With its absence, all
the statements blocks below the matched case label along with statements block of matched case
get executed. Usually, the result is unwanted.
 The statement block and break statement can be enclosed with in a pair of curly braces { and }.
 The default along with its statements block is an optional one. The break statement can be placed
at the end of default statements block. The default statements block can be placed at any where in
the switch statement. If they placed at any other places other than at end, it is compulsory to
include a break statement at the end of default statements block.
 Next-statement is a valid C statement.
Whenever, switch statement is encountered, first the value of <exp> gets matched with case
values. If suitable match is found, the statements block related to that matched case gets executed. The
break statement at the end transfers the control to the Next-statement.
If suitable match is not found, the default statements block gets executed. After then the control
gets transferred to Next-statement.
The flow of control using switch statement is determined as follows:

Program #9
Write a program to check whether given alphabet is vowel or consonant
/* A program to check whether given alphabet is vowel or consonant*/
#include<stdio.h>
#include<ctype.h>
main()
{
char alpha;
printf(“\n Enter any alphabet:”);
scanf(“\n%c”,&alpha);
switch(tolower(alpha))
{
case ‘a’:
case ‘e’:
case ‘i’:
case ‘o’:
case ‘u’: printf(“\n Given alphabet is vowel:”); break;
default: printf(“\n Given alphbet is consonant”);
}
}
Run:
Enter any alphabet: z
Given alphabet is consonant
Program #10
Write a program to calculate areas of different shapes (square, rectangle, circle, triangle
(base & height) and triangle with 3 sides
/* A program to calculate areas of different shapes*/
#include<stdio.h>
# define PI 3.14.12
main()
{
int s,l,b,h,r,choice,a,c;
float area;
printf(“\n1.Square\n2.Rectangle\n3.Circle\n4.Triangle(base & height)\n5.Triangle(3 sides)”);
printf(“\n Enter your choice”);
scanf(“%d”,&choice);
switch(choice)
{
case 1: printf(“\n Enter side value:”);
scanf(“%d”,&s);
area=s*s;
break;
case 2: printf(“\n Enter length and breadth values:”);
scanf(“%d%d”,&l,&b);
area=l*b;
break;
case 3: printf(“\n Enter radius value:”);
scanf(“%d”,&r);
area=PI*r*r;
break;
case 4: printf(“\n Enter base and height values:”);
scanf(“%d%d”,&b,&h);
area=b*h;
break;
case 5: printf(“\n Enter 3 sides value:”);
scanf(“%d%d%d”,&a,&b,&c);
s=(a+b+c)/2;
area=sqrt(s*s-a*s-b*s-c);
break;
default: printf(“\n Wrong choice”);

}
printf(“\n Area=%f”,area);
}
Run:
1.Square
2.Rectangle
3.Circle
4.Triangle (base & height)
5.Triangle (3 sides)
Enter your choice: 1
Enter side value:4
Area=16.000000
Program #11
Write a program to perform basic arithmetic operations
/* A program to perform basic arithmetic operations*/
#include<stdio.h>
main()
{
int a,b,result;
char op;
printf(“\n Enter any two numbers:”);
scanf(“%d%d”,&a,&b);
printf(“\n Enter any arithmetic operator (+,-,*,/,%):”);
scanf(“\n%c”,&op);
switch(op)
{
case ‘+’: result=a+b;
break;
case ‘-’: result=a-b;
break;
case ‘*’: result=a*b;
break;
case ‘/’: result=a/b;
break;
case ‘%’: result=a%b;
break;
default: printf(“\n Invalid arithmetic operator”);
}
printf(“\n Result=%d”,result);
}
Run:
Enter any 2 numbers: 23 54
Enter any arithmetic operator (+, -, *, /, %):
/
Result=0

6.3. Conclusion
A control flow statement is a statement that is needed when we want to transfer control as we needed.
Each control statement has its own property. Based on that property, the control gets transferred. The
conditional control statement causes the execution of one or more statements based on particular
condition. Looping control statement causes the repeated execution of one or more statements as long as
the condition is satisfied. The jumping control flow statement transfers the control to the specified position
without the need of satisfying the condition. These jumping control-flow statements transfer the control
unconditionally.
1)#include<stdio.h> 3)#include<stdio.h> 6)#include<stdio.h>
main() main() main()
{ { {
int a=300,b=10,c=20; int x=10; if(‘Z’<’z’)
if(!(a>=400)) if x>=2 printf(“\n Hello”);
b=300; printf(“%d”,x); else
c=200; } printf(“\n Hi”);
printf(“%d\t%d”,b,c); }
} 4)#include<stdio.h>
main() 7)#include<stdio.h>
2)#include<stdio.h>
{ main()
main()
if(!3.14) {
{
printf(“\n IAS”); float a=12.25,b=13.65;
int a=300,b=10,c=20;
else if(a=b)
if(!a>=400)
printf(“\n IPS); } printf(“\nequal”);
b=300;
c=200; else
5)#include<stdio.h> printf(“\n not equal”);
printf(“%d\t%d”,b,c); main()
} }
OBSERVABLE {
9)#include<stdio.h> int x=10,y=100%90; 8)#include<stdio.h>

O main()
{
float a=12.36; }
if(x!=y);
printf(“x=%d\ty=%d”,x,y);
main()
{
float a=0.7;

U if(a==12.36) if(a<0.7)
printf(“\nequal”); printf(“\nstoned”);
else 14)#include<stdio.h> else
main()
T
printf(“\n not equal”); printf(“\n Avenged”);
} { }
int k=-2,j=4;
switch(k/=j/k) 12)#include<stdio.h>

P
10)#include<stdio.h>
main() { main()
{ default: {
int x=100; printf(“beautiful”); int x=10,y=20;

U if(!!x)
printf(“x=%d”,!x);
case 0:
printf(“Handsome”);
case 1:
if(!(!x)&&x)
printf(“%d”,x);
else
else

T printf(“x=%d”,x); printf(“Smart”); printf(“%d”,y);


} case 2: }
printf(“pretty”);
} 13)#include<stdio.h>
11)#include<stdio.h>
} main()
main()
{ {
float a=0.5,b=0.9; int i=400*400/400;
if(a&&b>0.9) if(i==400)
printf(“Master”); printf(“Delhi”);
else else
printf(“Minister”); printf(“Dubai”);
} }
1)#include<stdio.h> 2)#include<stdio.h> 3)#include<stdio.h>
main() main() main()
{ { {
int i; char s=3; int i=3;
printf(“Enter any num:”); switch(s) switch(i)
scanf(“%d”,&i); { {
OBSERVABLE switch(i) case ‘1’: case 1:
{ printf(“one\n”); printf(“Moon”);

O case 1:
printf(“Sa”);
case 2:
case ‘2’:
printf(“two\n”);
break;
case 2:
printf(“Sky”);
break;

U
printf(“Ri”); default: case 3:
case 3: printf(“Three”); continue;
printf(“Ga”); } default:
printf(“Civil”);
T
case default: printf(“stars….”);
printf(“pa”); } }
} }
}
P
U
T
1) Rewrite the following set of statements using conditional operator:
int a=1,b;
if(a>10)
Q b=20;

2) Determine whether the following are true or false


U a) When if statements are nested, the last else gets associated with the nearest if without an
else.
E b) One if can have more than one else statement.
c) A switch statement can always be replaced by a series of if…else statements.
d) A switch expression can be of any type
S e) A program stops its execution when a break statement is encountered?

T 3) Find out errors, if any, in each of the following segments


a) if(x+y=z &&y>0)
I printf(“ “);
b) if(code>1);
a=b+c
O else
a=0
N c) if(p<0)||(q<0)
printf(“\n Sign is negative”);
S
/* A program to check whether three given /* A program to check type of triangle based
numbers are pythagorean triplets or not*/ on 3 given sides*/
#include<stdio.h> #include<stdio.h>
main() main()
{ {
int a,b,c; int a,b,c;
printf(“\n Enter any three numbers:”); printf(“\n Enter 3 sides values:”);
scanf(“%d%d%d”,&a,&b,&c); scanf(“%d%d%d”,&a,&b,&c);
if(a<b && a<c) if(a==b&&a==c)
{ printf(“\n Equilateral triangle”);
if(c*c==a*a+b*b) else if (a==b||b==c||a==c)
printf(“\n A Pythagorean triplet”); printf(“\n Isosceles triangle”);
else else
printf(“\n Not a Pythagorean triplet”); printf(“\n Scalane triangle”);
} }
else
printf(“\n Not a Pythagorean triplet”);
}

/* A program to calculate income tax /* A program to calculate grade


based on following conditions based on following conditions (3 subjects)
Income Tax if any subject is scored lesser than 35, failed
Below 50000 No tax avg grade
Rs 50000-100000 10% Above 70 First class with distinction
Rs 100000-1.5 lakhs 20%+1000 60-70 First class
Above 1.5 lakhs 30%+3000*/ 50-60 Second class
#include<stdio.h> Below 50 third class*/
main() #include<stdio.h>
{ main()
double gross,tax; {
printf(“Enter annual income:”); int m1,m2,m3;
scanf(“%lf”,&gross); float avg;
if(gross>=50000) printf(“\n Enter 3 subjects marks:”);
tax=0; scanf(“%d%d%d”,&m1,&m2,&m3);
else if(gross>=50000 &&gross<100000) if(m1<35||m2<35||m3<35)
tax=(gross*10)/100.0; printf(“\n You are failed”);
else if(gross>=100000 &&gross<150000) else
tax=1000+(gross*20)/100.0; {
else avg=(m1+m2+m3)/3.0;
tax=3000+(gross*30)/100.0; if(avg>=70)
printf(“\n Tax to be paid=Rs. %.2lf”,tax); printf(“\n First class with distinction”);
} else if(avg>=60 && avg<70)
printf(“\n First class”);
else if(avg>=50 && avg<60)
printf(“\n Second class”);
else
printf(“\n Third class”);
}
}

You might also like