9
Session
Loop
Concepts
Objectives
At the end of this session, you will be able to:
Understand the ‘for’ loop in C
Work with the ‘comma’ operator
Understand nested loops
Understand the ‘while’ loop and the ‘do-while’ loop
Work with ‘break’ and ‘continue’ statements
Understand the ‘exit()’ function
Introduction
One of the greatest advantages of a computer is its capability to execute a series of instructions repeatedly.
This is achieved by the loop structures available in a programming language. In this session you will learn
the various loop structures in C.
9.1 The Loop Structure
A loop is a section of code in a program which is executed repeatedly, until a specific condition is satisfied.
The loop concept is fundamental to structured programming.
The loop structures available in C are:
The for loop
The while loop
The do…while loop
The condition which controls the execution of the loop is coded using the Relational and Logical
operators in C.
Elementary Programming with C Version 1.1 © Aptech Limited page 139 of 356
Session 9
Loop
9.1.1 The ‘for’ Loop
Concepts
The general syntax of the for loop is:
for(initialize counter; conditional test; re-evaluation parameter)
{
Statement(s);
}
The initialize counter is an assignment statement that sets the loop control variable, before entering
the loop. This statement is executed only once. The conditional test is a relational expression, which
determines when the loop will exit. The re-evaluation parameter defines how the loop control variable
changes (mostly, an increment or decrement in the variable set at the start) each time the loop is repeated.
These three sections of the for loop must be separated by semicolons. The statement, which forms the
body of the loop, can either be a single statement or a compound statement (more than one statement).
The for loop continues to execute as long as the conditional test turns out to be true. When the
condition becomes false, the program resumes with the statement following the for loop.
Consider the following program:
Example 1:
/*This program demonstrates the for loop in a C program */
#include <stdio.h>
main()
{
int count;
printf(“\tThis is a \n”);
for(count = 1; count <=6 ; count++)
printf(“\n\t\t nice”);
printf(“\n\t\t world. \n”);
}
The sample output is shown below :
This is a
nice
nice
nice
nice
page 140 of 356 Version 1.1 © Aptech Limited Elementary Programming with C
Session 9
Loop
nice
Concepts
nice
world.
Look at the for loop section in the program.
1. The initialization parameter is count = 1
It is executed only once when the loop is entered, and the variable count is set to 1.
2. The conditional test is count <=6
A test is made to determine whether the current value of count is less than or equal to 6. If the test
is true, then the body of the loop is executed.
3. The body of the loop consists of a single statement
printf(“\n\n\t nice”);
This statement can be enclosed in braces to make the body of the loop more visible.
4. The re-evaluation parameter is count++ , increments the value of count by 1 for the next
iteration.
The steps 2,3,4 are repeated until the conditional test becomes false. The loop will be executed 6 times
for value of count ranging from 1 to 6. Hence, the word nice appears six times on the screen. For the
next iteration, count is incremented to 7. Since this value is greater than 6, the loop is ended and the
statement that follows it is executed.
The following program prints even numbers from 1 to 25.
Example 2:
#include <stdio.h>
main()
{
int num;
printf(“The even numbers from 1 to 25 are:\n\n”);
for(num=2; num <= 25; num+=2)
printf (“%d\n”,num);
}
Elementary Programming with C Version 1.1 © Aptech Limited page 141 of 356
Session 9
Loop
The output for the above code will be:
Concepts
The even numbers from 1 to 25 are:
2
4
6
8
10
12
14
16
18
18
20
22
24
The for loop above initializes the integer variable num to 2 (to get an even number) and increments it by
2 every time the loop is executed.
In for loops, the conditional test is always performed at the top of the loop. This means that the code
inside the loop is not executed if the condition is false in the beginning itself.
The ‘Comma’ operator
The scope of the for loop can be extended by including more than one initializations or increment
expressions in the for loop specification. The format is :
exprn1 , exprn2
The expressions are separated by the ‘comma’ operator and evaluated from left to right. The order of the
evaluation is important if the value of the second expression depends on the newly calculated value of
exprn1. This operator has the lowest precedence among the C operators.
The following example, which prints an addition table for a constant result, will illustrate the concept of
the comma operator clearly:
Example 3:
/* program illustrates the use of the comma operator */
#include <stdio.h>
page 142 of 356 Version 1.1 © Aptech Limited Elementary Programming with C
Session 9
Loop
main()
Concepts
{
int i, j , max;
printf(“Please enter the maximum value \n”);
printf(“for which a table can be printed: ”);
scanf(“%d”, &max);
for(i = 0 , j = max ; i <=max ; i++, j--)
printf(“\n%d + %d = %d”,i, j, i + j);
}
A sample output is shown below :
Please enter the maximum value -
for which a table can be printed: 5
0 + 5 = 5
1 + 4 = 5
2 + 3 = 5
3 + 2 = 5
4 + 1 = 5
5 + 0 = 5
Note that in the for loop, the initialization parameter is
i = 0, j = max
When it is executed , i is assigned the value 0 and j is assigned the value present in max.
The re-evaluation (increment) parameter again consists of two expressions:
i++, j--
after each iteration, i is incremented by 1 and j is decremented by 1. The sum of these two variables
which is always equal to max is printed out.
‘Nested for’ Loops
A for loop is said to be nested when it occurs within another for loop. The code will be something
like this:
Elementary Programming with C Version 1.1 © Aptech Limited page 143 of 356
Session 9
Loop
for(i = 1; i < max1; i++)
Concepts
{
.
.
for(j = 0; j < = max2; j++)
{
.
.
}
.
.
}
Consider the following example,
Example 4:
#include <stdio.h>
main()
{
int i, j, k;
i = 0;
printf(”Enter no. of rows :”);
scanf(”%d”, &i);
printf(“\n”);
for(j = 0; j < i ; j++)
{
printf(“\n”);
for (k = 0; k <= j; k++) /*inner for loop */
printf(“*”);
}
}
This program displays ‘*’ on each line and for each line increments the number of ‘*’ to be printed
by 1. It takes the number of rows for which ‘*’ has to be displayed as input. For example, if the input
is 5, the output will be
page 144 of 356 Version 1.1 © Aptech Limited Elementary Programming with C
Session 9
Loop
Concepts
**
***
****
*****
More on ‘for’ loops
The for loop can be used without one or all of its definitions.
For example,
.
.
for(num = 0; num ! = 255;)
{
printf(“Enter no. “);
scanf(“%d”, &num);
.
.
}
The above will accept a value for num until the input is 255. This loop does not have any re-
evaluation factor. The loop terminates when num becomes 255.
Similarly, consider
.
.
printf(“Enter value for checking :”);
scanf(“%d”, &num);
for(; num < 100; )
{
.
.
}
This loop does not have an initialization factor or a re-evaluation factor.
The for loop, when used without any definitions, gives an infinite loop.
Elementary Programming with C Version 1.1 © Aptech Limited page 145 of 356
Session 9
Loop
for( ; ; )
Concepts
printf(“This loop will go on and on and on ...\n”);
However, a break statement used within this loop will cause an exit from it.
.
.
for( ; ; )
{
printf(“This will go on and on”);
i = getchar();
if(i == ‘X’ || i == ‘x’)
break;
}
.
.
The above loop will run until the user enters x or X.
The for loop (or any other loop) can also be used without the body (statements). This helps to
increase the efficiency of some algorithms and to create time delay loops.
for(i = 0; i < xyz_value, i++);
is an example of a time delay loop.
9.1.2 The ‘while’ Loop
The second kind of loop structure in C is the while loop. Its general syntax is:
while(condition is true)
statement;
where, statement is either an empty statement, a single statement or a block of statements. If a set
of statements are present in a while loop then they must be enclosed inside curly braces { }. The
condition may be any expression. The loop iterates while this condition is true. The program control is
passed to the line after the loop code, when the condition becomes false.
The for loop can be used provided the number of iterations are known before the loop starts executing,
When the number of iterations to be performed is not known before hand, the while loop can be used.
page 146 of 356 Version 1.1 © Aptech Limited Elementary Programming with C
Session 9
Loop
Example 5:
Concepts
/* A simple program using the while loop */
#include <stdio.h>
main()
{
int count = 1;
while( count <= 10)
{
printf(“\n This is iteration %d\n”,count);
count++;
}
printf(“\n The loop is completed. \n”);
}
A sample output is shown below:
This is iteration 1
This is iteration 2
This is iteration 3
This is iteration 4
This is iteration 5
This is iteration 6
This is iteration 7
This is iteration 8
This is iteration 9
This is iteration 10
The loop is completed.
The program initially sets the value of count to 1 in the declaration statement itself. The next statement
executed is the while statement. The condition is first checked. The current value of count is 1, which
is less than 10. The condition test results is true, and therefore the statements in the body of the while
loop are executed. Therefore, they are enclosed within curly braces { }. The value of count becomes 2
after 1st iteration. Then the condition is checked again. This process is repeated until the value of count
becomes greater than 10. When the loop is exited, the second printf() statement is executed.
Like for loops, while loops check the condition at the top of the loop. This means that the loop code is
not executed, if the condition is false at the start.
The conditional test in the loop may be as complex as required. The variables in the conditional test may
be reassigned values within the loop, but a point to remember is that eventually the condition test must
Elementary Programming with C Version 1.1 © Aptech Limited page 147 of 356
Session 9
Loop
become false otherwise the loop will never end. The following is an example of an infinite while loop.
Concepts
Example 6:
#include <stdio.h>
main ()
{
int count = 0;
while(count < 100)
{
printf(“This goes on forever, HELP!!!\n”);
count+=10;
printf(“\t%d”, count);
count-=10;
printf(“\t%d”, count);
printf(“\nCtrl-C will help”);
}
}
In the above, count is always 0, which is less than 100 and so the expression always returns a true
value. Hence the loop never ends.
If more than one condition is to be checked to end a while loop, the loop will end if at least one of the
conditions become false. The following example illustrates this.
Example 7:
#include <stdio.h>
main()
{
int i, j;
i = 0;
a = 10;
while(i < 100 && a > 5)
{
.
.
i++;
a-= 2;
}
page 148 of 356 Version 1.1 © Aptech Limited Elementary Programming with C
Session 9
Loop
Concepts
.
}
This loop will perform 3 iterations, the first time a will be 10, the next time it will be 8 and the third time it
will be 6. After this though i is still less than 100 (i is 3), a takes the value 4, and the condition a>5 turns
out to be false, so the loop ends.
Let us write a useful program. It accepts input from the console and prints it on the screen.
The program ends when you press ^Z (Ctrl+Z).
Example 8:
/* ECHO PROGRAM */
/* A program to accept input data from the console and print it on the
screen */
/* End of input data is indicated by pressing ‘^Z’ */
# include <stdio.h>
main()
{
char ch;
while((ch = getchar()) != EOF)
{
putchar(ch);
}
}
A sample output is shown below :
Have
Have
a
a
good
good
day
day
^ z
Elementary Programming with C Version 1.1 © Aptech Limited page 149 of 356
Session 9
Loop
The user input is highlighted. How does this program work? After entering a set of characters, the contents
will get echoed back to the screen only when you press <Return>. This is because the characters you
Concepts
enter through the keyboard gets stored in the keyboard buffered input and the putchar() statement
fetches it from the buffer when you press <Return>. Notice how the input is terminated with a ^Z, which
is the end of file character on MS DOS operating system.
9.1.3 The ‘do .... while’ Loop
The do...while loop is sometimes referred to as the do loop in C. Unlike for and while loops, this
loop checks its condition at the end of the loop, that is after the loop has been executed. This means that
the do.... while loop will execute at least once, even if the condition is false at first.
The general syntax of the do... while loop is:
do {
statement;
} while (condition);
The curly brackets are not necessary when only one statement is present within the loop, but it is a good
habit to use them. The do...while loop iterates until the condition becomes false. In the do...while
loop the statement (block of statements) is executed first, then the condition is checked. If it is true,
control is transferred to the do statement. When the condition becomes false, control is transferred to
the statement after the loop.
Consider the following program :
Example 9:
/*accept only int values */
#include <stdio.h>
main ()
{
int num1, num2;
num2 = 0;
do{
printf( “\nEnter a number : “);
scanf(“%d”,&num1);
printf( “ No. is %d”,num1);
num2++;
}while(num1 != 0);
printf(“\nThe total numbers entered were %d”,--num2);
page 150 of 356 Version 1.1 © Aptech Limited Elementary Programming with C
Session 9
Loop
/* num2 is decremented before printing because count for last integer (0)
is not to be considered */
Concepts
}
A sample output is shown below:
Enter a number : 10
No. is 10
Enter a number : 300
No. is 300
Enter a number : 45
No. is 45
Enter a number : 0
No. is 0
The total numbers entered were 3
The above code will accept integers and display them until zero (0) is entered. It will then, exit from the
do...while loop and print the number of integers entered.
‘Nested while’ and ‘do...while’ Loops
Like for loops, while and do...while loops can also be nested. An example is given below:
Example 10:
#include <stdio.h>
main()
{
int x;
char i, ans;
i = ‘ ’;
do
{
x = 0;
ans = ‘y’;
printf(“\nEnter sequence of character:”);
do {
i = getchar ();
x++;
Elementary Programming with C Version 1.1 © Aptech Limited page 151 of 356
Session 9
Loop
}while (i != ‘\n’);
Concepts
i = ‘ ’;
printf(“\nNumber of characters entered is: %d”, --x);
printf(“\nMore sequences (Y/N) ?”);
ans = getchar();
}while(ans == ‘Y’ || ans == ‘y’);
}
A sample output is shown below:
Enter sequence of character:Good Morning !
Number of characters entered is: 14
More sequences (Y/N) ? N
This program code first asks the user to enter a sequence of characters till the enter key is hit
(nested while). Once the Enter key is pressed, the program exits from the inner do…while loop.
The program then asks the user if more sequences of characters are to be entered. If the user
types ‘y’ or ‘Y’, the outer while condition is true and the program prompts the user to enter another
sequence. This goes on till the user hits any other key except ‘y’ or ‘Y’. The program then ends.
9.2 Jump Statements
C has four statements that perform an unconditional branch: return, goto, break, and continue.
Unconditional branching means the transfer of control from the point where it is, to a specified statement.
Of the above jump statements, return and goto can be used anywhere in the program, whereas
break and continue statements are used in conjunction with any of the loop statements.
9.2.1 The ‘return’ Statement
The return statement is used to return from a function. It causes execution to return to the point at
which the call to the function was made. The return statement can have a value with it, which it returns
to the program. The general syntax of the return statement is:
return expression ;
The expression is optional. More than one return can be used in a function. However the function will
return when the first return is met. The return statement will be clear after a discussion on functions.
page 152 of 356 Version 1.1 © Aptech Limited Elementary Programming with C
Session 9
Loop
9.2.2 The ‘goto’ Statement
Concepts
Though C is a structured programming language, it contains the following unstructured forms of program
control:
goto
label
A goto statement transfers control not only to any other statement within the same function in a C
program, but it allows jumps in and out of blocks. Therefore, it violates the rules of a strictly structured
programming language.
The general syntax of the goto statement is,
goto label;
where label is an identifier which must appear as a prefix to another C statement in the same function.
The semicolon(;) after the label identifier marks the end of the goto statement. goto statements in
a program make it difficult to read. They reduce program reliability and make the program difficult to
maintain. However, they are used because they can provide useful means of getting out of deeply nested
loops. Consider the following code:
for(...){
for(...) {
for(...) {
while(..) {
if(...) goto error1;
.
.
.
}
}
}
}
error1: printf(“Error !!!”);
As seen, the label appears as a prefix to another statement in the program.
label: statement
or
Elementary Programming with C Version 1.1 © Aptech Limited page 153 of 356
Session 9
Loop
label: {
Concepts
statement sequence
}
Example 11:
# include <stdio.h>
main()
{
int num ;
label1:
printf(“\nEnter a number (1) :”);
scanf(“%d”,&num);
if(num==1)
goto Test;
else
goto label1:
Test:
printf(“All done…”);
}
A sample output is given below:
Enter a number : 4
Enter a number : 5
Enter a number : 1
All done...
9.2.3 The ‘break’ Statement
The break statement has two uses. It can be used to terminate a case in the switch statement and/or
to force immediate ending of a loop, bypassing the normal loop conditional test.
When the break statement is met inside a loop, the loop is immediately ended and the program control
is passed to the statement following the loop. For example,
page 154 of 356 Version 1.1 © Aptech Limited Elementary Programming with C
Session 9
Loop
Example 12:
Concepts
#include <stdio.h>
main ()
{
int count1, count2;
for(count1 = 1, count2 = 0; count1 <=100; count1++)
{
printf(“Enter %d Count2 : “, count1);
scanf(“%d”, &count2);
if(count2 == 100) break;
}
}
A sample output is shown below:
Enter 1 count2 : 10
Enter 2 count2 : 20
Enter 3 count2 : 100
In the above code, the user can enter 100 values for j. However, if 100 is entered, the loop ends and
control is passed to the next statement.
Another point to be remembered while using a break is that it causes an exit from an inner loop. This
means that if a for loop is nested within another for loop, and a break statement is encountered in the
inner loop, the control is passed back to the outer for loop.
9.2.4 The ‘continue’ Statement
The continue statement causes the next iteration of the enclosing loop to being. When this statement
is met in the program, the remaining statements in the body of the loop are skipped and the control is
passed to the re-initialization step.
In case of the for loop, continue causes the increment portions of the loop and then the conditional test
to be executed. In case of the while and do...while loops, program control passes to the conditional
tests. For example:
Example 13:
#include <stdio.h>
main ()
Elementary Programming with C Version 1.1 © Aptech Limited page 155 of 356
Session 9
Loop
{
Concepts
int num;
for(num = 1; num <=100; num++)
{
if (num % 9 == 0) continue;
printf(“%d\t”, num);
}
}
The above prints all numbers from 1 to 100, which are not divisible by 9. The output will look somewhat
like this.
1 2 3 4 5 6 7 8 10 11 12 13 14 15 16 17
19 20 21 22 23 24 25 26 28 29 30 31 32 33 34 35
37 38 39 40 41 42 43 44 46 47 48 49 50 51 52 53
55 56 57 58 59 60 61 62 64 65 66 67 68 69 70 71
73 74 75 76 77 78 79 80 82 83 84 85 86 87 88 89
91 92 93 94 95 96 97 98 100
9.3 The ‘exit()’ function
The exit() function is a standard C library function. Its working is similar to the working of a jump
statement, the major difference being that the jump statements are used to break out of a loop, whereas
exit() is used to break out of the program. This function causes immediate ending of the program
and control is transferred back to the operating system. The exit() function is usually used to check
if a mandatory condition for a program execution is satisfied or not. The general syntax of the exit()
function is
exit(int return_code);
where, return_code is optional. Zero is generally used as a return_code to indicate normal program
ending. Other values indicate some sort of error.
page 156 of 356 Version 1.1 © Aptech Limited Elementary Programming with C
Session 9
Loop
Summary
Concepts
The loop structures available in C are:
The for loop
The while loop
The do...while loop
The for loop enables repeated execution statements in C. It uses three expressions,
separated by semicolons, to control the looping process. The statement part of the loop
can be simple statement or a compound statement.
The ‘comma’ operator is occasionally useful in the for statements . Of all the operators in C
it has the lowest priority.
The body of a do statement is executed at least once.
C has four statements that perform an unconditional branch : return, goto, break, and
continue.
The break statement enables early exit from a simple or a nesting of loops. The continue
statement causes the next iteration of the loop to begin.
A goto statement transfers control to any other statement within same function in a C
program, but it allows jumps in and out of blocks.
The exit() function causes immediate termination of the program and control is transferred
back to the operating system.
Elementary Programming with C Version 1.1 © Aptech Limited page 157 of 356
Session 9
Loop
Check Your Progress
Concepts
1. _________ allows a set of instructions to be performed until a certain condition is
reached.
A. Loop B. Structure
C. Operator D. None of the above
2. _________ loops check the condition at the top of the loop which means the loop code is
not executed, if the condition is false at the start.
A. while loop B. for loop
C. do..while loop D. None of the above
3. A ___________ is used to separate the three parts of the expression in a for loop.
A. comma B. semicolon
C. hyphen D. None of the above
4. The _________ loop checks its condition at the end of the loop, that is after the loop has
been executed.
A. while loop B. for loop
C. do..while loop D. None of the above
5. The _______ statement causes execution to return to the point at which the call to the
function was made.
A. exit B. return
C. goto D. None of the above
6. The _______ statement violates the rules of a strictly structured programming language.
A. exit B. return
page 158 of 356 Version 1.1 © Aptech Limited Elementary Programming with C
Session 9
Loop
Check Your Progress
Concepts
C. goto D. None of the above
7. The _________ function causes immediate termination of the program and control is
transferred back to the operating system
A. exit B. return
C. goto D. None of the above
Elementary Programming with C Version 1.1 © Aptech Limited page 159 of 356