0% found this document useful (0 votes)
7 views21 pages

Unit 6 - V1

This document is a course material for C Programming at Manipal University Jaipur, focusing on loops and flow control in C. It covers the while loop, do...while loop, and for loop, explaining their syntax, use cases, and providing example programs. Additionally, it includes self-assessment questions and exercises to reinforce learning.
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)
7 views21 pages

Unit 6 - V1

This document is a course material for C Programming at Manipal University Jaipur, focusing on loops and flow control in C. It covers the while loop, do...while loop, and for loop, explaining their syntax, use cases, and providing example programs. Additionally, it includes self-assessment questions and exercises to reinforce learning.
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/ 21

C Programming Manipal University Jaipur (MUJ)

BACHELOR OF COMPUTER APPLICATIONS


SEMESTER 1

C PROGRAMMING

Unit 6 : Flow of Control Part 2 1


C Programming Manipal University Jaipur (MUJ)

Unit 6
Flow of Control Part 2
Table of Contents

SL Fig No / Table SAQ /


Topic Page No
No / Graph Activity
1 Introduction - -
3
1.1 Objectives - -
2 The While Loop - 1 4-7
3 The Do…While Loop - 2 7-9
4 THE For LOOP - -
10-15
4.1 The Nesting Of For Loops - 3
5 The Break Statement And Continue Statement - - 15-17
6 Summary - - 18
7 Terminal Questions - - 19-20
8 Answers To Self Assessment Questions - - 20
9 Answers To Terminal Questions - - 20
10 Exercises - - 20-21

Unit 6 : Flow of Control Part 2 2


C Programming Manipal University Jaipur (MUJ)

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:

At studying this unit, you should be able to:

❖ Understand the basic concepts of loops in C programming.


❖ Learn to implement 'for', 'while', and 'do-while' loops in C.
❖ Explore common use cases and best practices for loop usage.

Unit 6 : Flow of Control Part 2 3


C Programming Manipal University Jaipur (MUJ)

2. THE WHILE LOOP

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.)

The general syntax of a while loop is

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

Unit 6 : Flow of Control Part 2 4


C Programming Manipal University Jaipur (MUJ)

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.)

Unit 6 : Flow of Control Part 2 5


C Programming Manipal University Jaipur (MUJ)

Program 1: Program to find largest of n numbers

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++;
}

printf("\n large = %d”, large);


}

Program 2: Program to evaluate sine series sin(x)=x-x^3/3!+x^5/5!-x^7/7!+-----


depending on accuracy

#include<stdio.h>
#include <math.h> void main()
{
int n, i=1,count;
float acc, x, term, sum;

Unit 6 : Flow of Control Part 2 6


C Programming Manipal University Jaipur (MUJ)

printf("enter the angle\n");


scanf(“%d”, &x); x=x*3.1416/180.0;
printf(“\nenter the accuracy)";
scanf(“%f”, &acc);
sum=x;
term=x;
while ((fabs(term))>acc)
{
term=-term*x*x/((2*i)*(2*i+1)); sum+=term;
i++;
}
printf"\nsum of sine series is %f", sum);
}

SELF-ASSESSMENT QUESTIONS - 1
1. A ______________ loop starts out like an if statement .
2. while is an entry-controlled loop. (True/False)

3. THE DO…WHILE LOOP

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 loop takes the following form:

Unit 6 : Flow of Control Part 2 7


C Programming Manipal University Jaipur (MUJ)

do

Body of the loop

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.

Program 6.3: A program to print the multiplication table from 1 x 1 to 10 x 10 as shown


below using do-while loop.

1 2 3 4 …………………… 10

2 4 6 8 …………………… 20

3 6 9 12 …………………… 30

4 …………………… 40

. .

. .

. .

10 100

Unit 6 : Flow of Control Part 2 8


C Programming Manipal University Jaipur (MUJ)

Program to print multiplication table main()

{
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)

Unit 6 : Flow of Control Part 2 9


C Programming Manipal University Jaipur (MUJ)

4. THE for LOOP

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.

Generally, the syntax of a for loop is

for(expr1; expr2; expr3) statement(s)

(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 :

for (i = 0; i < 10; i = i + 1)

printf("i is %d\n", i);

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:

Unit 6 : Flow of Control Part 2 10


C Programming Manipal University Jaipur (MUJ)

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(;;)

...

Unit 6 : Flow of Control Part 2 11


C Programming Manipal University Jaipur (MUJ)

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.

The powers-of-two example using for is:

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

for(expr1; expr2; expr3)


statement

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)
{

Unit 6 : Flow of Control Part 2 12


C Programming Manipal University Jaipur (MUJ)

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.)

Program 3: A Program to find the factorial of a number

void main()
{
int M,N;
long int F=1;

Unit 6 : Flow of Control Part 2 13


C Programming Manipal University Jaipur (MUJ)

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)

4.1. The Nesting of for loops


Nesting of for loops, that is, one for statement within another for statement, is allowed in C.
For example, two loops can be nested as follows:

………
………
for(i=1;i<10;i++)
{
…….
…….

Unit 6 : Flow of Control Part 2 14


C Programming Manipal University Jaipur (MUJ)

for(j=1;j<5;j++)
{
……
……
}
…….
…….
}
………
………

5. THE BREAK STATEMENT AND CONTINUE STATEMENT

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;

Program 4: Program to illustrate the use of break statement.

void main ( )
{
int x;
for (x=1; x<=10; x++)
{
if (x==5)

Unit 6 : Flow of Control Part 2 15


C Programming Manipal University Jaipur (MUJ)

break; /*break loop only if x==5 */


printf(“%d”, x);
}
printf (“\nBroke out of loop”);
printf( “at x =%d“);
}

The above program displays the numbers from 1to 4 and prints the message “Broke out of
loop when 5 is encountered.

The continue statement

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;

Program 5: Program to illustrate the use of continue statement.

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”);
}

Unit 6 : Flow of Control Part 2 16


C Programming Manipal University Jaipur (MUJ)

The above program displays the numbers from 1to 10, except the number 5.

Program 6: Program to sum integers entered interactively

#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;
}

Unit 6 : Flow of Control Part 2 17


C Programming Manipal University Jaipur (MUJ)

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.

Unit 6 : Flow of Control Part 2 18


C Programming Manipal University Jaipur (MUJ)

7. TERMINAL QUESTIONS

1. Write the output that will be generated by the following C program:

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);
}

2. Write the output that will be generated by the following C program:

void main()
{
int i=0, x=0;
do
{
if (i%5 == 0)
{

Unit 6 : Flow of Control Part 2 19


C Programming Manipal University Jaipur (MUJ)

x++;
printf(“%d\t”, x);
}
++i;
} while (i<20);
printf(“\nx=%d”, x);
}

8. ANSWERS TO SELF ASSESSMENT QUESTIONS

1. while
2. true
3. do…while
4. false
5. false
6. true

9. ANSWERS TO TERMINAL QUESTIONS

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

Unit 6 : Flow of Control Part 2 20


C Programming Manipal University Jaipur (MUJ)

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.

Unit 6 : Flow of Control Part 2 21

You might also like