0% found this document useful (0 votes)
20 views23 pages

Pop Module2

Chapter 10 covers decision control and looping statements in C programming, including if, if-else, switch, and goto statements for decision making. It also introduces iterative statements such as while, do, and for loops, explaining their syntax and usage for executing code based on conditions. The chapter emphasizes the importance of these control structures in managing the flow of execution in programs.

Uploaded by

madhukeshs0742
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views23 pages

Pop Module2

Chapter 10 covers decision control and looping statements in C programming, including if, if-else, switch, and goto statements for decision making. It also introduces iterative statements such as while, do, and for loops, explaining their syntax and usage for executing code based on conditions. The chapter emphasizes the importance of these control structures in managing the flow of execution in programs.

Uploaded by

madhukeshs0742
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 23

Chapter 10

DECISION CONTROL AND LOOPING


STATEMENTS
LEARNING OBJECTIVES

o Discuss decision making with if statement.


o Describe if….else statement.
o Explain switch statement.
o Know conditional operator.
o Illustrate how goto statement is used for unconditional branching.

10.1 INTRODUCTION TO DECISION CONTROL SYSTEM

We have seen that a C program is a set of statement which is normally executed


sequentially in the order in which they appear. This happens when no options or repetitions of
certain calculations are necessary. In practice, we have number of situations where we may
have to change the order of execution of statements based on certain condition, or repeat a
group of statements until certain specified conditions are met. This involves a kind of
decision making to see whether a particular condition has occurred or not and then direct the
computer to execute certain statements accordingly.

C language possesses such decision making capabilities by supporting the following


statements:
 if statement
 if-else statement
 nested if statement
 nested if-else statement
 switch statements
 goto statement
These statements are popularly called as decision-making statement. Since these statements
‘control’ the flow of execution, they are also known as control statements.
A selection statement is a conditional statement allows choosing between two or more
execution paths in a program. Most modern programming languages include one-way, two-
way and n-way (multiple) selections.
 An if statement with no else part is a one-way selector.
 An if-else statement is a two-way selector.
 A switch or case statement is an n-way selector.
10.2 CONDITIONAL BRANCHING STATEMENTS
10.2.1 if statement
The if statement is a powerful decision-making statement and is used to control the
flow of execution of statements. It is basically a two-way decision statement and is used in
conjunction with an expression. But only if statement is a one way selection which executes
statements based on whether conditional statement is true/false. Relational operators <
=,<,>,= =, > = and != are used to specify conditions.

Syntax: if(test expression)


{
statement(s);
}

This allows the computer to evaluate the expression first and then, depending on whether the
value of expression is true(or non zero) or false(zero), it transfers the control to a particular
statement.

Example: Program to check the eligibility for pension after retirement from service

#include<stdio.h>
#include<conio.h>
void main()
{
int age;
printf(“Enter age of person:\n”);
scanf(“%d”,&age);
if(age>60)
printf(“Eligible for pension”);
if(age<60)
printf(“Not eligible for pension”);
getch();
}

Output:
1> Enter age of person: 56
Not eligible for pension

2> Enter age of person: 62


Eligible for pension

10.2.2 if…else statement


The if…else statement is an extension of the simple if condition statement. if..else
statement is two way selection statement which executes statements when the conditional
expression in the if is true, if it is false then statement under else are executed.
Syntax:

if(test expression)
{
True-block statement(s)
}
else
{
False-block statement(s)
}
Statement-x

If the test expression is true, then the true block statement(s), immediately following the if
statements are executed, otherwise, the false block statement(s) are executed. In earlier case,
either true or false block will be executed, not both. This is illustrated in below flowchart.

Fig. 2: Flowchart of if…else control

Example: Program to check the eligibility for pension after retirement from
service.(using if…else condition)

#include<stdio.h>
#include<conio.h>
void main()
{
int age;
printf(“Enter age of person:\n”);
scanf(“%d”,&age);
if(age>60)
printf(“Eligible for pension”);
else
printf(“Not eligible for pension”);
getch();
}

Output:
1> Enter age of person: 59
Not eligible for pension

2> Enter age of person: 66


Eligible for pension

Nesting of if…else statements(Nested if..else)


When a series of decisions are involved, we may have to use more than one if…else
statement in nested form as shown in figure 3 below. if..else statements within an if or else of
if..else statement is called nested if…else.

Fig. 3: Flow of nested if…else statements

The logic (syntax) of execution is illustrated in figure 4. If the test expression is false,
it enters to nested test expression otherwise it continues to perform body of if. If the nested
test expression is true body of nested if is executed, otherwise body of nested else will
perform and then control will transfer to the statement below to if.
Fig. 4: Flowchart of nested if…else statements.
Example: C program to find maximum between three numbers using nested if..else
#include <stdio.h>
int main()
{
/* Declare three integer variables */
int num1, num2, num3;
/* Input three numbers from user */
printf("Enter three numbers: ");
scanf("%d%d%d", &num1, &num2, &num3);
if(num1 > num2)
{
if(num1 > num3)
{
/* If num1>num2 and num1>num3 */
printf("%d is max.", num1);
}
else
{
/* If num1>num2 but num1<num3 */
printf("%d is max.",num3);
}
}
else
{
if(num2 > num3)
{
/* If num1<num2 and num2>num3 */
printf("%d is max.",num2);
}
else
{
/* If num1<num2 and num2<num3 */
printf("%d is max.",num3);
}
}
return 0;
}
Output:
Enter three numbers: 25
58
47
58 is max
10.2.3 if-else-if statement (else if ladder/cascaded if-else)
When we have multiple options available or we need to take multiple decisions based
on available condition, we can use another form of if statement called else…if ladder.
In else…if ladder each else is associated with another if statement. Evaluation of condition
starts from top to down. If condition becomes true then the associated block with if statement
is executed and rest of conditions are skipped. If the condition becomes false then it will
check for next condition in a sequential manner. It repeats until all conditions are cheeked or
a true condition is found. If all condition available in else…if ladder evaluated to false then
default else block will be executed. This construct is known as the else if ladder. The
conditions are evaluated from the top, downwards. This can be shown in the flowchart shown
in figure 5.
Syntax:
if (condition 1)
{
// block 1
}
else if (codition 2)
{
// block 2
}
else if(codition 3)
{
// block 3
}
else
{
// default block }
Fig.5: Flowchart of else..if ladder.

Example:
#include<stdio.h>
#include<conio.h>
void main()
{
int x, y, z, ch;
clrscr();
printf("\n1.Addition\n2.Subtraction\n3.Multiplication\4.Division\n");
printf("\nEnter your choice :");
scanf("%d", &ch);
printf("\nEnter X and Y :");
scanf("%d %d", &x, &y);
if (ch == 1)
{
z = x + y;
}
else if (ch == 2)
{
z = x - y;
}
else if(ch == 3)
{
z = x * y;
}
else if(c == 4)
{
z = x/y ;
}
else
{
printf("\n Invalid choice! Please try again!");
}
printf("\n Answer is %f", z);
getch();
}

Output:
1> 1.Addition
2.Subtraction
3.Multiplication
4.Division
Enter your choice :
2
Enter X and Y :37 12
Answer is 25.000000
2> 1.Addition
2.Subtraction
3.Multiplication
4.Division
Enter your choice :
3
Enter X and Y :37 12
Answer is 444.000000
3> 1.Addition
2.Subtraction
3.Multiplication
4.Division
Enter your choice :
9
Invalid choice! Please try again!
10.2.4 Switch case
When multiple decisions involved in the program at that time we can use else…if
ladder but some time it is difficult to read and understand. In addition to this when the
numbers of alternative are more than the complexity of the program will also get increase. In
such situation C-Language provides another multi-way decision making statement called
switch statement. Switch statement tests a value against the different value. If the value is
matched, then the corresponding group of statements are executed. Switch statement begins
with switch keyword.
The structure of switch statement is more standard and readable then the else if
ladder. Switch statement uses different cases to be matched. It will match the expression
value with different cases available in switch statement from the top to down ward. Each case
has its associated block of statement. Matching of the case value will perform from the first
case. As soon as it founds the matching case, statements associated with that case block is
executed and remaining cases are skipped. If no matching case is found then the default block
will be executed if present. The default is optional if present then it will be executed
otherwise no action will be taken.
Rules for Switch statement:
o Switch expression must be of type integer or character.
o Each case value must be unique that means no two case value should be same.
o Default is optional it can be place anywhere in switch statement but normally it is
place at the end.
o Break statement is also optional if not present then similar cases will be executed.

Fig. 6: Selection process of switch statement

Matching of case expression will be start from top to the down when it found
matching case the block associated with that case expression executes then after control
transfers to the statement-x. If case expression doesn’t match next case expression will be
tested in sequential manner up to the last case and if no matching case is found, default block
will be executed if present.
Example: Program to demonstrate the use of switch statement for basic calculation
#include<stdio.h>
#include<conio.h>
void main()
{
float x, y, ans;
int ch;
clrscr();
printf("\n1.Addition\n2.Subtraction\n3.Multiplication\4.Division\n");
printf("\nEnter your choice :");
scanf("%d", &ch);
printf("\nEnter X and Y :");
scanf("%f %f", &x, &y);
switch(ch)
{
case 1:
ans = x + y;
break;
case 2:
ans = x - y;
break;
case 3:
ans = x * y;
break;
case 4:
ans = x / y;
break;
default:
printf("\n Invalid choice! Please try again!");
}
printf("\n Answer is %.2f", ans);
getch();
}
Output:
1> 1.Addition
2.Subtraction
3.Multiplication
4.Division
Enter your choice :
2
Enter X and Y :37 12
Answer is 25.00
2> 1.Addition
2.Subtraction
3.Multiplication
4.Division
Enter your choice :
3
Enter X and Y :37 12
Answer is 444.00
3> 1.Addition
2.Subtraction
3.Multiplication
4.Division
Enter your choice :
9
Invalid choice! Please try again!
Table 10.1: Comparison between the switch and if-else construct

10.3 ITERATIVE STATEMENTS (DECISION MAKING AND LOOPING)


LEARNING OBJECTIVES
o Discuss while statement
o Explain do statement
o Describe for statement
o Illustrate how jumps are applied in loops
Introduction
C-programming language provides one of the most powerful features known as looping
structure. When we want to execute some statements repeatedly based on some specific condition
looping structure can be helpful. Iterative statements are loops refer to repetitive execution of same set
of instructions for a given number of times until a result is obtained. Looping structure can be divided
into the following two categories:

 Entry control loop


 Exit control loop
Entry control loop Exit control loop
 An entry control loop checks the  An Exit Control Loop checks the
condition at the time of entry and if condition for exit and if given
condition or expression becomes condition for exit evaluates to true,
true then control transfers into the control will exit from the loop
body of the loop. body else control will enter again
 Such type of loop controls entry to into the loop.
the loop that’s why it is called  Such type of loop controls exit of
entry control loop. the loop that’s why it is called exit
 Test condition is checked first, and control loop.
then loop body will be executed.  Loop body will be executed first,
 If Test condition is false, loop body and then condition is checked.
will not be executed.  If Test condition is false, loop body
Ex: while, for loop will be executed at least once.
Ex: do while

What are Loops?


In looping, a program executes the sequence of statements many times until the stated
condition becomes false. A loop consists of two parts, a body of a loop and a control
statement. The control statement is a combination of some conditions that direct the body of
the loop to execute until the specified condition becomes false.
10.3.1 while Loop
A while loop is the most straightforward looping structure. It executes statements
until the condition of the while loop evaluates to true. Loop gets terminated when condition
become false. The basic format of while loop is as follows:
Syntax:
while (test condition)
{
statements; /*body of loop }
It is an entry-controlled loop. In while loop, a condition is evaluated before processing
a body of the loop. If a condition is true then and only then the body of a loop is executed.
After the body of a loop is executed then control again goes back at the beginning, and the
condition is checked if it is true, the same process is executed until the condition becomes
false. Once the condition becomes false, the control goes out of the loop.
After exiting the loop, the control goes to the statements which are immediately after
the loop. The body of a loop can contain more than one statement. If it contains only one
statement, then the curly braces are not compulsory. It is a good practice though to use the
curly braces even we have a single statement in the body.
In while loop, if the condition is not true, then the body of a loop will not be executed,
not even once. It is different in do while loop which we will see shortly.

Fig. 7: while loop construct


Example: Following program illustrates a while loop:
#include<stdio.h>
#include<conio.h>
int main()
{
int num=1; //initializing the variable
while(num<=10) //while loop with condition
{
printf("%d\n",num);
num++; //incrementing operation
}
return 0;
}

Output:
1
2
3
4
5
6
7
8
9
10
The above program illustrates the use of while loop. In the above program, we have
printed series of numbers from 1 to 10 using a while loop.

(1) We have initialized a variable called num with value 1. We are going to print from
1 to 10 hence the variable is initialized with value 1. If you want to print from 0, then assign
the value 0 during initialization.
(2) In a while loop, we have provided a condition (num<=10), which means the loop
will execute the body until the value of num becomes 10. After that, the loop will be
terminated, and control will fall outside the loop.
(3) In the body of a loop, we have a print function to print our number and an
increment operation to increment the value per execution of a loop. An initial value of num is
1, after the execution, it will become 2, and during the next execution, it will become 3. This
process will continue until the value becomes 10 and then it will print the series on console
and terminate the loop.
Note: - \n is used for formatting purposes which means the value will be printed on a
new line

10.3.2 do-While loop


A do-while loop is similar to the while loop except that the condition is always
executed after the body of a loop. The while loop construct as we discussed in previous
section, makes a test of condition before the loop is executed. Therefore, the body of the loop
may not be executed at all if the condition is not satisfied at very first attempt. do-while is
also called an exit-controlled loop.
Syntax:

do
{
Statements; /* body of loop
} while (expression);

As we saw in a while loop, the body is executed if and only if the condition is true. In
some cases, we have to execute a body of the loop at least once even if the condition is false.
This type of operation can be achieved by using a do-while loop.
In the do-while loop, the body of a loop is always executed at least once. After the
body is executed, then it checks the condition. If the condition is true, then it will again
execute the body of a loop otherwise control is transferred out of the loop.
Similar to the while loop, once the control goes out of the loop the statements which
are immediately after the loop is executed.
The critical difference between the while and do-while loop is that in while loop the
while is written at the beginning. In do-while loop, the while condition is written at the end
and terminates with a semi-colon (;)

Fig. 8: do-while loop construct


Example: Following program illustrates the working of a do-while loop:
We are going to print a table of number 2 using do while loop.
#include<stdio.h>
#include<conio.h>
int main()
{
int num=1; //initializing the variable
do //do-while loop
{
printf("%d\n",2*num);
num++; //incrementing operation
}while(num<=20);
return 0;
}
Output:
2
4
6
8
10
12
14
16
18
20
In the above example, we have printed multiplication table of 2 using a do-while loop.
Let's see how the program was able to print the series of number using do-while.

(1) We have initialized a variable 'num' with value 1. Then we have written a do-
while loop.
(2) In a loop, we have a print function that will print the series by multiplying the
value of num with 2.
(3) After each increment, the value of num will increase by 1, and it will be printed on
the screen.
(4) Initially, the value of num is 1. In a body of a loop, the print function will be
executed in this way: 2*num where num=1, then 2*1=2 hence the value two will be printed.
Then the num will be incremented by 1 (num++=num+1), now 2*num where num value is 2,
then 2*2=4, hence value 4 is printed. This will go on until the value of num becomes 10.
After that loop will be terminated and a statement which is immediately after the loop will be
executed.
2.3.3 for loop
A for loop is a more efficient loop structure in 'C' programming. It is also most used
and preferred looping statement. for loop consists of three parts. The general structure of for
loop is as follows:
Syntax:
for(initial value; test-condition; incrementation or decrementation )
{
statements;
}

 The initial value of the for loop is performed only once.

 The test-condition is a Boolean expression that tests and compares the


counter to a fixed value after each iteration, stopping the for loop when false is
returned.

 The incrementation/decrementation increases (or decreases) the counter by


a set value.

Example: Following program illustrates the use of a simple for loop:


#include<stdio.h>
int main()
{
int number;
for(number=1;number<=10;number++) //for loop to print 1-10 numbers
{
printf("%d\n",number); //to print the number
}
return 0;
}
Output:
1
2
3
4
5
6
7
8
9
10
The above program prints the number series from 1-10 using for loop.
(1) We have declared a variable called number of an int data type to store values.

(2) In for loop, in the initialization part, we have assigned value 1 to the variable
number. And remember that the initial value of the for loop is performed only once. In the
condition part, we have specified our condition and then the increment part.

(3) In the body of a loop, we have a print function to print the numbers on a new line
in the console. We have the value one stored in number, after the first iteration the value will
be incremented, and it will become 2. Now the variable number has the value 2. The
condition will be rechecked and since the condition is true loop will be executed, and it will
print two on the screen. This loop will keep on executing until the value of the variable
becomes 10. After that, the loop will be terminated, and a series of 1-10 will be printed on the
screen.

Fig. 9: for loop construct


Additional features of for loop

 In C, the for loop can have multiple expressions separated by commas in each part.
For example:
for (x = 0, y = num; x < y; i++, y--)
{
statements;
}

 We can skip the initial value expression, condition and/or increment by adding a
semicolon.
For example:
int i=0;
int max = 10;
for (; i < max; i++)
{
printf("%d\n", i);
}
 Notice that loops can also be nested where there is an outer loop and an inner loop.
For each iteration of the outer loop, the inner loop repeats its entire cycle.
10.4 NESTED LOOPS
A nested loop means a loop statement inside another loop statement. That is why
nested loops are also called “loop inside loops“. Any number of loops can be defined inside
another loop, i.e., there is no restriction for defining any number of loops. The nesting level
can be defined at n times.
Syntax:
for ( initialization; condition; increment )
{
for ( initialization; condition; increment )
{
// statement of inside loop
}
// statement of outer loop
}
Fig. 10: nested for loop construct
Consider the following example, that uses nested for loops output a multiplication table:
#include <stdio.h>
int main()
{
int i, j;
int table = 2;
int max = 5;
for (i = 1; i <= table; i++) // outer loop
{
for (j = 0; j <= max; j++)
{
printf("%d x %d = %d\n", i, j, i*j); // inner loop
}
printf("\n"); /* blank line between tables */
}
}

Output:
1x0=0
1x1=1
1x2=2
1x3=3
1x4=4
1x5=5

2x0=0
2x1=2
2x2=4
2x3=6
2x4=8
2 x 5 = 10
The nesting of for loops can be done up-to any level. The nested loops should be
adequately indented to make code readable. In some versions of 'C,' the nesting is limited up
to 15 loops, but some provide more.
The nested loops are mostly used in array applications which we will see in further
tutorials.
10.5 BREAK AND CONTINUE STATEMENTS (Unconditional Control Transfer
Statements)
Unconditional Control Transfer Statements is used to transfers the control to some
other place/block in the program. In C Programming Language, There are three types of
unconditional control transfer statements.
 break statement
 continue statement
 goto statement
10.5.1 break statement
A break statement can be used to terminate or to come out from the loop or
conditional statement unconditionally. It can be used in switch statement to break and come
out from the switch statement after each case expression. Whenever, break statement is
encounter within the program then it will break the current loop or block. A break statement
is normally used with if statement. When certain condition becomes true to terminate the loop
then break statement can be used.

Fig. 11: Working of brake statement in different loops

In the following program demonstrates the use of break statement. Loop will be
terminated as soon as the counter value becomes greater than 5.
Example: Program to demonstrate the use of continue

#include<stdio.h>
#include<conio.h>
void main()
{
int i;
clrscr();
for( i = 1; i <= 10 ; i++ )
{
if (i > 5)
break; // terminate loop
printf("\n %d ", i);
}
getch();
}

10.5.2 continue statement:


A continue statement can be used into the loop when we want to skip some statement
to be executed and continue the execution of above statement based on some specific
condition. Similar to break statement, continue is also used with if statement. When compiler
encounters continue, statements after continue are skip and control transfers to the statement
above continue.

Fig. 12: Working of continue statement in while loop.


The following example uses the continue statement to print upper and lower a to z alphabets
Example: Program to print upper and lower a to z alphabets using continue
#include<stdio.h>
#include<conio.h>
void main()
{
int i;
clrscr();
for ( i = 65 ; i<=122; i++ ) // loop through ASCII value for a to z
{
if(i >= 91 && i <= 96)
continue ; // skip unnecessary special characters between 91 and 96
printf(" %c " , i ) ; // print character equivalent for ASCII value.
}
getch();
}

10.6 GOTO STATEMENT:


C-language provides goto statement to transfer control unconditionally to other part of
the program. Although use of goto statement is not advisable but sometime it is desirable to
use go to statement. It has the following form:

Fig. 13: Working of goto statement.

goto statement requires a label to determine where to transfer the control. A label
must end with colon (:). We can use any valid name as a label similar to variable name. When
compiler encounters goto statement with a label name then, it transfers the control to the
location where label has been defined in the program
When we use goto statement either some statement are execute repeatedly or skipped.
When goto statement is placed after the label, control jumps backward direction and some
statement are repeated. Such type of go to jump is called backward jump. When goto
statement is placed before the label in the program, control transfers to the label and some
statements are skipped. Such type of jump is called forward jump. In highly structure
programming language such as c, it is not advisable to use go to statement. We should avoid
using go to statement as far as possible because it affects performance of the program.
The following program demonstrates the use of goto statement.
Example: /* without goto and label */ /* without goto and label */
#include<stdio.h> #include<stdio.h>
void main() void main()
{ {
printf(“Davangere \t”); printf(“Davangere \t”);
printf(“is a \t”); goto label;
printf(“smart city”); printf(“is a \t”);
} lable: printf(“smart city”);
Output: }
Davangere is a smart city Output:
Davangere smart city

You might also like