0% found this document useful (0 votes)
93 views18 pages

Computer Programming & Problem Solving (CPPS-I) : Chapter # 3

The document discusses different types of loops in C language including for, while, and do-while loops. It provides details on the structure and usage of for loops, including the initialize, test, and increment expressions. An example for loop code is provided that prints the numbers from 0 to 9. It explains that for loops are well-suited for situations that require repeating an action a fixed number of times.

Uploaded by

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

Computer Programming & Problem Solving (CPPS-I) : Chapter # 3

The document discusses different types of loops in C language including for, while, and do-while loops. It provides details on the structure and usage of for loops, including the initialize, test, and increment expressions. An example for loop code is provided that prints the numbers from 0 to 9. It explains that for loops are well-suited for situations that require repeating an action a fixed number of times.

Uploaded by

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

CE-102: CPPS-1 ( Chapter # 3 ) Batch 2003

Computer Programming & Problem Solving ( CPPS-I )

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

There are 3 types loop structures in C Language i.e

 For Loop
 While Loop
 Do-While Loop

1. For Loop

It is often the case in programming that you want to do something a fixed


number of times. Perhaps you want to calculate the paycheck for 100
employees or print out the squares of all the numbers from 1 to 50.
The for loop is ideally suited for such cases.

Let’s look at a simple example of a for loop.

Program

void main (void)

{
int count;
clrscr( );

for ( count = 0; count < 10; count + + )

printf ( “ Count = %d \n “, count );


getch( );

Sir Syed University of Engineering & Technology Page 1 of 18


CE-102: CPPS-1 ( Chapter # 3 ) Batch 2003

Output:

Count = 0
Count = 1
Count = 2
Count = 3
Count = 4
Count = 5
Count = 6
Count = 7
Count = 8
Count = 9

This program’s role in technical life is to execute a printf( ) statement 10 times.


The printf ( ) function prints out the phrase “ Count = “ followed by the value of
the variable count.

Structure of the for loop

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

Expression Name Purpose

Count = 0 Initialize expression Initialize loop variable

Count < 10 Test Expression Test loop variable

Count + + Increment expression Increment loop variable

For example: for ( count = 0; count < 10; count + + )

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.

Sir Syed University of Engineering & Technology Page 2 of 18


CE-102: CPPS-1 ( Chapter # 3 ) Batch 2003

The Initialize Expression

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 Test Expression

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 Increment Expression

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.

The Body of the For Loop

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:

printf ( “ Count = %d \n “, count );

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.

Sir Syed University of Engineering & Technology Page 3 of 18


CE-102: CPPS-1 ( Chapter # 3 ) Batch 2003

Operation of the For Loop

Let us follow the operation of the loop, as depicted in the figure given below.

Enter

Initialize

Test

Exit
Body of the Loop

Increment

Sir Syed University of Engineering & Technology Page 4 of 18


CE-102: CPPS-1 ( Chapter # 3 ) Batch 2003

Program

void main (void)


{
int count;
clrscr( );

for ( count = 0; count < 10; count + + )

printf ( “ Count = %d \n “, count );


getch( );
}

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.

Multiple Statements in For Loop

In for loop two or more statements can be also used, in the program.

Program

void main (void)


{
int count;
int total = 0;
clrscr( );

for ( count = 0; count < 10; count + + )

{
total = total + count;
printf ( “ Count = %d, Total = %d \n “, count, total );
}

getch( );
}

Sir Syed University of Engineering & Technology Page 5 of 18


CE-102: CPPS-1 ( Chapter # 3 ) Batch 2003

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.

Loop Style Note

Many C programmers, handle braces in a some what different way than we have
used in the above example:

for ( count = 0; count < 10; count + + ) {


total = total + count;
printf ( “ Count = %d, Total = %d \n “, count, total );
}

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.

An ASCII Table Program

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

Sir Syed University of Engineering & Technology Page 6 of 18


CE-102: CPPS-1 ( Chapter # 3 ) Batch 2003

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

/* Print table of ASCII Character */

void main (void)


{
int n;
clrscr( );

for ( n = 1; n < 256; n + + )

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.

What is actually stored in the computer’s memory is an integer n, as specified in


the type declaration statement. The %d format specifier prints the decimal
representation of n, while the %c format specifier prints the character whose
ASCII codes is n.

Nested For Loop

It is possible to nest one for loop inside another. For example a program that
prints out the multiplication of table.

Sir Syed University of Engineering & Technology Page 7 of 18


CE-102: CPPS-1 ( Chapter # 3 ) Batch 2003

Program

void main (void)


{
int cols, rows;
clrscr( );

for ( rows = 1; rows < 6; rows + + ) /* Outer Loop */


{
for ( cols = 1; cols < 6; cols + + ) /* Inner Loop */

printf ( “ %3d = “, cols * rows );


printf ( “ \n “ );
}
getch( );
}

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.

Sir Syed University of Engineering & Technology Page 8 of 18


CE-102: CPPS-1 ( Chapter # 3 ) Batch 2003

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

void main (void)


{
int count;
int total = 0;
clrscr( );

while ( count < 10 )

{
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

Sir Syed University of Engineering & Technology Page 9 of 18


CE-102: CPPS-1 ( Chapter # 3 ) Batch 2003

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.

The Unexpected Conditions

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

void main (void)


{
int count;
clrscr( );

printf ( “ Type in a phrase: \n “ );

while ( getch ( ) ! = ‘ \r ‘ )

count + + ;
printf ( “ \n Character Count is = %d ”, count );
}

Output:

Type in a phrase:
Pakistan
Character Count is = 8

Sir Syed University of Engineering & Technology Page 10 of 18


CE-102: CPPS-1 ( Chapter # 3 ) Batch 2003

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 While Loop

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.

The expression ( getch ( ) ! = ‘ \r ‘ ) incorporates the function getch ( ), returns the


value of a character the instant the character is typed, so the function can be
treated like a variable and compared with other variables or constants.

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

void main (void)


{
int count = -1;
char ch = ‘a’;
clrscr( );

printf ( “ Type in a phrase: \n “ );

while ( ch ! = ‘ \r ‘ )

Sir Syed University of Engineering & Technology Page 11 of 18


CE-102: CPPS-1 ( Chapter # 3 ) Batch 2003

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.

ASCII Revisited Program

void main (void)


{
char ch = ‘a’;
clrscr( );

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

Sir Syed University of Engineering & Technology Page 12 of 18


CE-102: CPPS-1 ( Chapter # 3 ) Batch 2003

The code for b is 98


Enter a Character:
A
The code for A is 65

Nested While Loops

The following program follows a WHILE loop nested in a FOR loop.

Program

void main (void)


{
int m;
char ch = ‘a’;
clrscr( );

for ( m = 0; m < 5; m + + )
{
printf ( “ \n Type in a letter from ‘a’ to ‘e’ : \n “ );

while ( ( ch = getche ( ) ) != ‘d’ )


{
printf ( “ \n Sorry, %c is incorrect. \n “, ch );
printf ( “ Try again. \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

Type in a letter from ‘a’ to ‘e’ :


a
Sorry, a is incorrect.
Try Again
c
Sorry, c is incorrect.
Try Again
d

Sir Syed University of Engineering & Technology Page 13 of 18


CE-102: CPPS-1 ( Chapter # 3 ) Batch 2003

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.

Assignment Expression as values in a loop

while ( ( ch = getche ( ) ) != ‘ d ‘ )

ch = getche ( )

ch = ‘a’

‘a’ != ‘d’

Precedence: Assignment versus relational operators.

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.

Mathematical WHILE loop

Program

void main (void)


{
long number = 1;
long answer;

while ( number != 0 )
{
printf ( “ \n Enter a number: “);
scanf ( “ %ld “, &number );
answer = 1;

Sir Syed University of Engineering & Technology Page 14 of 18


CE-102: CPPS-1 ( Chapter # 3 ) Batch 2003

while ( number > 1 )


answer = answer * number - - ;
printf ( “ Factorial is %ld \n “, answer );
}
}

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.

Integer value capacity is: 32,767


Long value holds upto: 2,147,483,647

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 )

Sir Syed University of Engineering & Technology Page 15 of 18


CE-102: CPPS-1 ( Chapter # 3 ) Batch 2003

Program

void main (void)


{
int count = 0;
int total = 0;
clrscr( );

do
{
total = total + count;
printf ( “ Count = %d, Total = %d \n “, count + +, total );
}

while ( count < 10 ) ;

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 operation of the Do while Loop is sort of an upside-down version of the


While loop. The body of the loop is first executed, then the test condition is
checked. If the test condition is true, the loop is repeated; if it is false, the loop
terminates. The body of the loop will always be executed at least once, sine the
test condition is not checked until the end of the loop.

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.

Sir Syed University of Engineering & Technology Page 16 of 18


CE-102: CPPS-1 ( Chapter # 3 ) Batch 2003

Operation of the Do While Loop

Let us follow the operation of the loop, as depicted in the figure given below.

Enter Loop

Body of the Loop

Increment

Test

Exit Loop

Sir Syed University of Engineering & Technology Page 17 of 18


CE-102: CPPS-1 ( Chapter # 3 ) Batch 2003

Summary of Loop in C Language.

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.

Sir Syed University of Engineering & Technology Page 18 of 18

You might also like