Unit 6 - V1
Unit 6 - V1
C PROGRAMMING
Unit 6
Flow of Control Part 2
Table of Contents
1. INTRODUCTION
In the prior unit, you explored decision control statements in C. This unit focuses on utilizing
loops in C, pivotal for automating repetitive tasks. C offers three main loop types: 'for', 'while',
and 'do-while', each with distinct applications. The 'for' loop is ideal for predetermined
iterations, 'while' for indefinite conditions, and 'do-while' for executing at least once.
Through this unit, you'll master loop syntax, understand optimal use cases, and explore
advanced concepts like nested loops. Do…while loop is used in a situation where we need to
execute the body of the loop before the test is performed. The for loop is used to execute the
body of the loop for a specified number of times. The break statement is used to exit any loop
In C programming, the continue statement is used within loops to skip the remaining code
within the current iteration of the loop and proceed directly to the next iteration.
1.1. Objectives:
Loops generally consist of two parts: one or more control expressions which control the
execution of the loop, and the body, which is the statement or set of statements which is
executed over and over.
The most basic loop in C is the while loop. A while loop has one control expression, and
executes as long as that expression is true. Here before executing the body of the loop, the
condition is tested. Therefore it is called an entry-controlled loop. The following example
repeatedly doubles the number 2 (2, 4, 8, 16, ...) and prints the resulting numbers as long as
they are less than 1000:
int x = 2;
while(x < 1000)
{
printf("%d\n", x);
x = x * 2;
}
(Once again, we've used braces {} to enclose the group of statements which are to be
executed together as the body of the loop.)
while( expression )
statement(s)
A while loop starts out like an if statement: if the condition expressed by the expression is
true, the statement is executed. However, after executing the statement, the condition is
tested again, and if it's still true, the statement is executed again. (Presumably, the condition
depends on some value which is changed in the body of the loop.) As long as the condition
remains true, the body of the loop is executed over and over again. (If the condition is false
right at the start, the body of the loop is not executed at all.)
As another example, if you wanted to print a number of blank lines, with the variable n
holding the number of blank lines to be printed, you might use code like this:
while(n > 0)
{
printf("\n");
n = n - 1;
}
After the loop finishes (when control “falls out'' of it, due to the condition being false), n will
have the value 0.
You use a while loop when you have a statement or group of statements which may have to
be executed a number of times to complete their task. The controlling expression represents
the condition “the loop is not done'' or “there's more work to do.'' As long as the expression
is true, the body of the loop is executed; presumably, it makes at least some progress at its
task. When the expression becomes false, the task is done, and the rest of the program
(beyond the loop) can proceed. When we think about a loop in this way, we can see an
additional important property: if the expression evaluates to “false'' before the very first trip
through the loop, we make zero trips through the loop. In other words, if the task is already
done (if there's no work to do) the body of the loop is not executed at all. (It's always a good
idea to think about the “boundary conditions'' in a piece of code, and to make sure that the
code will work correctly when there is no work to do, or when there is a trivial task to do,
such as sorting an array of one number. Experience has shown that bugs at boundary
conditions are quite common.)
main()
{
int num, large, n, i;
clrscr();
printf("enter number of numbers \n");
scanf(“%d”,&n);
large=0;
i=0;
while(i<n)
{
printf("\n enter number ");
scanf(“%d”, &num);
if(large<num)
large=num;
i++;
}
#include<stdio.h>
#include <math.h> void main()
{
int n, i=1,count;
float acc, x, term, sum;
SELF-ASSESSMENT QUESTIONS - 1
1. A ______________ loop starts out like an if statement .
2. while is an entry-controlled loop. (True/False)
The do…while loop is used in a situation where we need to execute the body of the loop
before the test is performed. Therefore, the body of the loop may not be executed at all if the
condition is not satisfied at the very first attempt. Where as while loop makes a test of
condition before the body of the loop is executed.
For above reasons while loop is called an entry-controlled loop and do..while loop is called
an exit-controlled loop.
do
while ( expression);
On reaching the do statement , the program proceeds to evaluate the body of the loop first.
At the end of the loop, the conditional expression in the while statement is evaluated. If the
expression is true, the program continues to evaluate the body of the loop once again. This
process continues as long as the expression is true. When the expression becomes false, the
loop will be terminated and the control goes to the statement that appears immediately after
the while statement.
On using the do loop, the body of the loop is always executed at least once irrespective of the
expression.
1 2 3 4 …………………… 10
2 4 6 8 …………………… 20
3 6 9 12 …………………… 30
4 …………………… 40
. .
. .
. .
10 100
{
int
rowmax=10,colmax=10,row,col,x;
printf(" Multiplication table\n");
printf("......................................\n");
row=1;
do
{
col=1
; do
{
x=row*col;
printf(“%4d”,
x); col=col+1;
}
while
(col<=colmax);
printf(“\n”);;
row=row+1;
}
while(row<=rowmax);
Printf("............................................................................................................\
n");
}
SELF-ASSESSMENT QUESTIONS - 2
3. On using the ________, the body of the loop is always executed at least once
irrespective of the expression.
4. do…while is an entry-controlled loop. (True/False)
The for loop is used to repeat the execution of set of statements for a fixed number of times.
The for loop is also an entry-controlled loop.
(Here we see that the for loop has three control expressions. As always, the statement can be
a brace-enclosed block.)
Many loops are set up to cause some variable to step through a range of values, or, more
generally, to set up an initial condition and then modify some value to perform each
succeeding loop as long as some condition is true. The three expressions in a for loop
encapsulate these conditions: expr1 sets up the initial condition, expr 2 tests whether
another trip through the loop should be taken, and expr3 increments or updates things after
each trip through the loop and prior to the next one. Consider the following :
In the above example, we had i = 0 as expr1, i < 10 as expr2 , i = i + 1 as expr3, and the call to
printf as statement, the body of the loop. So the loop began by setting i to 0, proceeded as
long as i was less than 10, printed out i's value during each trip through the loop, and added
1 to i between each trip through the loop.
When the compiler sees a for loop, first, expr1 is evaluated. Then, expr2 is evaluated, and if
it is true, the body of the loop (statement) is executed. Then, expr3 is evaluated to go to the
next step, and expr2 is evaluated again, to see if there is a next step. During the execution of
a for loop, the sequence is:
expr1
expr2
statement
expr3
expr2
statement
expr3
...
expr2
statement
expr3
expr2
The first thing executed is expr1. expr3 is evaluated after every trip through the loop. The
last thing executed is always expr2, because when expr2 evaluates false, the loop exits.
All three expressions of a for loop are optional. If you leave out expr1, there simply is no
initialization step, and the variable(s) used with the loop had better have been initialized
already. If you leave out expr2, there is no test, and the default for the for loop is that another
trip through the loop should be taken (such that unless you break out of it some other way,
the loop runs forever). If you leave out expr3, there is no increment step.
The semicolons separate the three controlling expressions of a for loop. (These semicolons,
by the way, have nothing to do with statement terminators.) If you leave out one or more of
the expressions, the semicolons remain. Therefore, one way of writing a deliberately infinite
loop in C is
for(;;)
...
It's also worth noting that a for loop can be used in more general ways than the simple,
iterative examples we've seen so far. The “control variable'' of a for loop does not have to be
an integer, and it does not have to be incremented by an additive increment. It could be
“incremented'' by a multiplicative factor (1, 2, 4, 8, ...) if that was what you needed, or it could
be a floating-point variable, or it could be another type of variable which we haven't met yet
which would step, not over numeric values, but over the elements of an array or other data
structure. Strictly speaking, a for loop doesn't have to have a “control variable'' at all; the
three expressions can be anything, although the loop will make the most sense if they are
related and together form the expected initialize, test, increment sequence.
int x;
for(x = 2; x < 1000; x = x * 2)
printf("%d\n", x);
There is no earth-shaking or fundamental difference between the while and for loops. In fact,
given the general for loop
you could usually rewrite it as a while loop, moving the initialize and increment expressions
to statements before and within the loop:
expr1;
while(expr2)
{
statement
expr3;
}
Similarly, given the general while loop
while(expr)
statement
you could rewrite it as a for loop:
for(; expr; )
statement
Another contrast between the for and while loops is that although the test expression
(expr2) is optional in a for loop, it is required in a while loop. If you leave out the controlling
expression of a while loop, the compiler will complain about a syntax error. (To write a
deliberately infinite while loop, you have to supply an expression which is always nonzero.
The most obvious one would simply be while(1) .)
If it's possible to rewrite a for loop as a while loop and vice versa, why do they both exist?
Which one should you choose? In general, when you choose a for loop, its three expressions
should all manipulate the same variable or data structure, using the initialize, test, increment
pattern. If they don't manipulate the same variable or don't follow that pattern, wedging
them into a for loop buys nothing and a while loop would probably be clearer. (The reason
that one loop or the other can be clearer is simply that, when you see a for loop, you expect
to see an idiomatic initialize/ test/increment of a single variable, and if the for loop you're
looking at doesn't end up matching that pattern, you've been momentarily misled.)
void main()
{
int M,N;
long int F=1;
clrscr();
printf(“enter the number\n”)";
scanf(“%d”,&N);
if(N<=0)
F=1;
else
{
for(M=1;M<=N;M++)
F*=M;
}
printf(“the factorial of the number is %ld”,F);
getch();
}
SELF-ASSESSMENT QUESTIONS - 3
5. for loop is an exit-controlled loop. (True/False)
6. The “control variable'' of a for loop does not have to be an integer. (True/False)
………
………
for(i=1;i<10;i++)
{
…….
…….
for(j=1;j<5;j++)
{
……
……
}
…….
…….
}
………
………
The purpose of break statement is to break out of a loop (while, do while, or for loop) or a
switch statement. When a break statement is encountered inside a loop, the loop is
immediately exited and the program continues with the statement immediately following
the loop. When the loops are nested, the break would only exit from the loop containing it.
That is, the break would exit only a single loop.
Syntax : break;
void main ( )
{
int x;
for (x=1; x<=10; x++)
{
if (x==5)
The above program displays the numbers from 1to 4 and prints the message “Broke out of
loop when 5 is encountered.
The continue statement is used to continue the next iteration of the loop by skipping a part
of the body of the loop (for, do/while or while loops). The continue statement does not
apply to a switch, like a break statement.
Unlike the break which causes the loop to be terminated, the continue, causes the loop to be
continued with the next iteration after skipping any statements in between.
Syntax: continue;
void main ( ) {
int x;
for (x=1; x<=10; x++)
{ if (x==5)
continue; /* skip remaining code in loop
only if x == 5 */
printf (“%d\n”, x);
}
printf(“\nUsed continue to skip”);
}
The above program displays the numbers from 1to 10, except the number 5.
#include <stdio.h>
int main(void)
{
long num;
long sum = 0L; /* initialize sum to zero */
int status;
printf("Please enter an integer to be summed. ");
printf("Enter q to quit.\n"); status = scanf("%ld", &num);
while (status == 1)
{
sum = sum + num;
printf("Please enter next integer to be summed. ");
printf("Enter q to quit.\n");
status = scanf("%ld", &num);
}
printf("Those integers sum to %ld.\n", sum);
return 0;
}
6. SUMMARY
The most basic loop in C is the while loop. A while loop has one control expression, and
executes as long as that expression is true. do..while loop is used in a situation where we
need to execute the body of the loop before the test is performed. The for loop is used to
execute the set of statements repeatedly for a fixed number of times. It is an entry controlled
loop. break statement is used to exit any loop. Unlike the break which causes the loop to be
terminated, the continue, causes the loop to be continued with the next iteration after
skipping any statements in between.
7. TERMINAL QUESTIONS
void main()
{
int i=0, x=0;
while (i<20)
{
if (i%5 == 0)
{
x+=i;
printf(“%d\t”, i);
}
i++;
}
printf(“\nx=%d”; x);
}
void main()
{
int i=0, x=0;
do
{
if (i%5 == 0)
{
x++;
printf(“%d\t”, x);
}
++i;
} while (i<20);
printf(“\nx=%d”, x);
}
1. while
2. true
3. do…while
4. false
5. false
6. true
1. 0 5 10 15
x = 30
2. 1 2 3 4
x=4
10. EXERCISES
1. Write a program to compute the sum of digits of a given number using while loop.
2. Write a program that will read a positive integer and determine and print its binary
equivalent using do…while loop.
3. The numbers in the sequence
1 1 2 3 5 8 13………..
are called Fibonacci numbers. Write a program using do…while loop to calculate
and print the first n Fibonacci numbers.