Computer Programming & Problem Solving (CPPS-I) : Chapter # 3
Computer Programming & Problem Solving (CPPS-I) : Chapter # 3
Loop
Chapter # 3
For Loop
While Loop
Do-While Loop
Almost always, if something is written worth doing, it is worth doing more than
once. You can probably think of several examples of this form in real life, such as
going to the TV program or eating a good dinner. Programming is the same; we
frequently need to perform an action over, often with variations in detail each
time. The mechanism that meets this need is the “loop”.
For Loop
While Loop
Do-While Loop
1. For Loop
Program
{
int count;
clrscr( );
Output:
Count = 0
Count = 1
Count = 2
Count = 3
Count = 4
Count = 5
Count = 6
Count = 7
Count = 8
Count = 9
The parenthesis following the keyword “for” contains what we will call the “loop”
expression. This loop expression is divided by semicolons into three separate
expressions i.e the “Initialize expression”, the “Test expression” and the
”Increment expression”.
The variable count occupies a key role in this fop loop. In conjunction with the 3
parts of the loop expression, count is used to control the operation of the loop.
Specially, it keeps track of how may times we have been through the loop.
The Initialize expression, count = 0; initializes the count variable. The Initialize
expression is always executed as soon as the loop is entered. We can start at
any number, in this case we initialize the count to 0. However, loops are often
started at 1 or some other number.
The second expression, count < 10, tests each time through the loop to see if
count is less than 10. To do this, it makes use of the relational operator for “less
than” ( < ), If the test expression is true i.e count is less than 10, than the body of
the loop i.e the printf ( ) statement will be executed. If the expression becomes
false i.e count is 10 or more, the loop will be terminated and control will pass to
the statements following the loop.
The third expression, count + + increments the variable count each time the loop
is executed. To do this, it uses the increment operator ( ++ ).
The loop variable in a for loop does not have to be increased by 1 each time
through the loop. It can be also decreased by 1.
Following the keyword for and the loop expression is the body of the loop: that is,
the statement or statements that will be executed each time round the loop. In
our first example there is only one statement:
Note
In a for loop, there is no semi colon between the loop expression and the body of
the loop. Since the keyword for and the loop expression and the statement
constituting the body of the loop are considered to be a single C statement.
Let us follow the operation of the loop, as depicted in the figure given below.
Enter
Initialize
Test
Exit
Body of the Loop
Increment
Program
First the initialization expression is executed, then the test condition is examined.
If the test expression is false to begin with, the body of the loop will not be
executed at all. If the condition is true, the body of the loop is entered and,
following that, the increment expression is executed. This is why the first number
printed out by our program is 0 and not the 1. Printing takes place before count is
incremented by the (++) operator. Finally the loop recycles and the test
expression is queried again. This will continue until the test expression becomes
false i.e count becomes 10, at which the loop will end.
In for loop two or more statements can be also used, in the program.
Program
{
total = total + count;
printf ( “ Count = %d, Total = %d \n “, count, total );
}
getch( );
}
Output:
Count = 0, Total = 0
Count = 1, Total = 1
Count = 2, Total = 3
Count = 3, Total = 6
Count = 4, Total = 10
Count = 5, Total = 15
Count = 6, Total = 21
Count = 7, Total = 28
Count = 8, Total = 36
Count = 9, Total = 45
The most important new feature of this program is the use of the additional
braces { { and } } to encapsulate the two statements that form the body of the
loop.
Assignment
Write the above program with the help of the Arithmetic Assignment Operator.
Many C programmers, handle braces in a some what different way than we have
used in the above example:
This has the advantage of saving a line in the listing. However, the compiler does
not care which way choose, and we feel that aligning the matching braces
vertically makes it easier to ensure that each opening brace vertically makes it
easier to ensure that each opening brace is matched by a closing brace and
helps to clarify the structure of the program. Both approaches are common but
for the ease of the programmer and user, one should use one-brace per line
approach.
Implementation of the For Loop to print out a table of ASCII codes. In the PC
family, each of the numbers from 0 to 255 represents a separate character. From
0 to 31 are the control codes such as the carriage return, tab and linefeed and
some of the graphics characters; from 32 to 127 are the usual printing
characters; and from 128 to 255 are graphics and foreign language characters.
Program
printf ( “ %3d = %c \ t “, n, n );
getch( );
}
Output:
61= = 62 = > 63 = ? 64 = à 65 = A 66 = B 67 = C 68 = D 69 = E 70 = F
71= G 72 = H 73 = I 74 = J 75 = K 76 = L 77 = M 78 = N 79 = O 80 = P
In C Language, we can use the same variable n, for both number and character;
only the format specifier changes: %c prints the character, while %d prints the
number. Format Specifier can interpret the same variable in different ways.
It is possible to nest one for loop inside another. For example a program that
prints out the multiplication of table.
Program
Output:
1 2 3 4 5
2 4 6 8 10
3 6 9 12 15
4 8 12 16 20
5 10 15 20 25
In this program the inner loop steps through 5 columns, from 1 to 5, while the
outer loop steps through 5 rows. For each row, the inner loop is cycled through
once; then a new line is printed in preparation for the next row. Each time through
the inner loop that is, at each intersection of a column and a row, the product of
the row number (rows) and the column number (cols) is printed by the printf
function.
For instance, if the variable cols was 3, meaning we are on the third column, and
rows was 4, meaning we are on the fourth row, then the program multiplies 3 by 4
and prints the product at the intersection of this row and column. Since we used
the “less than” operator (<), the loop variable cols and rows never reach the limit
of 6; i.e the loop both terminates at 5.
2. While Loop
The second kind of the loop structure available in C Language is the “While
Loop”. Although at first glance this structure seems to be simpler than the for
loop, it actually uses the same elements, but they are distributed throughout
the program.
The following program uses a while loop to reproduce the operation of our
earlier for loop program, which prints the number from 0 to 9 and gave the
running total.
Program
{
total = total + count;
printf ( “ Count = %d, Total = %d \n “, count + +, total );
}
getch( );
}
Output:
Count = 0, Total = 0
Count = 1, Total = 1
Count = 2, Total = 3
Count = 3, Total = 6
Count = 4, Total = 10
Count = 5, Total = 15
Count = 6, Total = 21
Count = 7, Total = 28
Count = 8, Total = 36
Count = 9, Total = 45
Certainly the expression in the parenthesis following the keyword while simpler
than the three part expression the for loop. It dispenses with the initialization and
increment expression, retaining only the test expression.
Operation of the While Loop
The loop variable count is initialize outside the loop in the declaration int count = 0.
When the loop is first entered, the condition count < 10 is tested. If it false, the loop
terminates. If it is true the body of the loop is executed. The increment expression is
buried in the body of the while loop. When the printf ( ) statement that forms the
loop body has finished printing, count is incremented by the (++) operator.
In situations, where the number if iterations in a loop are known in advance, as they
are in the while loop example, while loop are actually less appropriate.
In this case the for loop is a more natural choice, since we can use its explicit
initialize, test and increment expressions to control the loop.
So, when is the while loop becomes the appropriate choice?
The while loop shines, in situations where a loop may be terminated unexpectedly
by conditions developing with in the loop.
Program
while ( getch ( ) ! = ‘ \r ‘ )
count + + ;
printf ( “ \n Character Count is = %d ”, count );
}
Output:
Type in a phrase:
Pakistan
Character Count is = 8
This program invites you to type in a phrase. As you enter each character it
keeps a count of how many characters you have typed, and when you hit the
[Return] key it prints out the total.
Note
“ While Loop are more appropriate than the For Loop, when the condition
that terminates the loop occurs unexpectedly.”
Why is the while loop more appropriate in the above program than a for loop?
The loop on this program terminates when the character typed at the keyboard is
the [Return] character.
There is no need for a loop variable, since we do not have to keep track of where
we are in the loop, and thus no need for initialize or increment expressions.
Since there is no loop variable to initialize or increment, thus the while loop,
consisting only of the test expression, is the appropriate choice.
In the above program we compare it with the constant ‘ \r ‘, the carriage return
[Return] key.
Since we use the “ not equal “ operator ( ! = ), the while loop will continue to be
executed as long as it does encountered it, the loop will terminate and the total
number of characters typed will be printed out.
Program
while ( ch ! = ‘ \r ‘ )
ch = getche ( );
count + + ;
}
printf ( “ \n Character Count is = %d ”, count );
}
Output:
Type in a phrase:
Pakistan
Character Count is = 8
In this program, count variable must be initialized to an odd looking –1, value
because the program now checks with character is read after the loop is entered
instead of before.
while ( ch ! = ‘ \r ‘ )
{
printf ( “ Enter a Character: \n “ );
ch = getche ( );
printf ( “ \n The code for %c is %d. \n “, ch, ch );
}
This program asks the user to type a character and then prints out the ASCII
code for the character. It will do this over and over. It is more useful when you
only want to check the ASCII code one or two keyboard characters without
looking at the entire table.
Output:
Enter a Character:
a
The code for a is 97
Enter a Character:
b
Program
for ( m = 0; m < 5; m + + )
{
printf ( “ \n Type in a letter from ‘a’ to ‘e’ : \n “ );
printf ( “ \n That’s It ! \n “ );
}
printf ( “ Game’s Over ! \n “ );
}
This program let you guess a lower case letter ‘a’ to ‘e’ and tells you if you are
right or wrong.
Output
That’s It !
The outer for loop lets you play the game exactly five times. The inner while loop
determines whether your guess is correct. In this program you have only 5 tries
and after that inner loop terminates.
while ( ( ch = getche ( ) ) != ‘ d ‘ )
ch = getche ( )
ch = ‘a’
‘a’ != ‘d’
while ( ( ch = getche ( ) ) != ‘ d ‘ )
If the parentheses were not there, the compiler would interpret the expression
like this:
while ( ch = ( getche ( ) != ‘ d ‘ ) )
This of course is not what we want at all, since ch will now be set equal to the
results of a true/false expression. The reason we need the parenthesis is that the
precedence of the relational operator ( != ) is greater than of the assignment
operator ( = ). So unless parentheses, tell the compiler otherwise, the relational
operator ( ! = ) will be evaluated first.
Program
while ( number != 0 )
{
printf ( “ \n Enter a number: “);
scanf ( “ %ld “, &number );
answer = 1;
Output
Type number: 3
Factorial is: 6
Type number: 4
Factorial is: 24
Type number: 0
This program uses outer while loop to recycle until a 0 value is entered. The
inner loop uses the document operator to reduce the variable number ___ which
starts out at the value typed in number reaches to 1, the loop terminates.
3. Do-While Loop
The last of the three loops in C Language is the Do while Loop. This is very
similar to the while loop except that the test occurs at the end of the loop body.
This guarantees that the loop is executed at least once before continuing.
Such a setup is frequently used where data is to be read. The test then verifies
the data, and loops back to read again if it was unacceptable.
do
{
printf (" Enter the number : ");
scanf ("%d", &num);
}
while ( num < 25 )
Program
do
{
total = total + count;
printf ( “ Count = %d, Total = %d \n “, count + +, total );
}
getch( );
}
Output:
Count = 0, Total = 0
Count = 1, Total = 1
Count = 2, Total = 3
Count = 3, Total = 6
Count = 4, Total = 10
Count = 5, Total = 15
Count = 6, Total = 21
Count = 7, Total = 28
Count = 8, Total = 36
Count = 9, Total = 45
The do keyword marks the beginning of the loop, it has no other function. The
while keyword marks the end of the loop and contains the loop expression.
The important point to notice is that the body of the loop will be executed at least
once, since the test condition is not checked until the end of the loop.
Let us follow the operation of the loop, as depicted in the figure given below.
Enter Loop
Increment
Test
Exit Loop
C gives you a choice of three types of loops i.e for, while and do while loops.
The For Loop is frequently used, usually where the loop will be traversed
a fixed number of times. It is very flexible, and novice programmers should
take care not to abuse the power it offers.
The While Loop keeps repeating an action until an associated test returns
false. This is useful where the programmer does not know in advance how
many times the loop will be traversed.
The Do While Loop is similar to the While Loop, but the test occurs after
the loop body is executed. This ensures that the loop body is run at least
once.