0% found this document useful (0 votes)
24 views

Unit 7 - Looping With While, Do-While and For

This document discusses loops in C programming. It introduces the three types of loops: while loops, do-while loops, and for loops. It provides examples of each loop type and explains how they work. Key aspects covered include initializing and updating variables, evaluating conditional expressions, and using loop bodies with single statements or blocks of statements. Complex expressions involving multiple variables can also be used within the components of for loops.

Uploaded by

barnabas
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
24 views

Unit 7 - Looping With While, Do-While and For

This document discusses loops in C programming. It introduces the three types of loops: while loops, do-while loops, and for loops. It provides examples of each loop type and explains how they work. Key aspects covered include initializing and updating variables, evaluating conditional expressions, and using loop bodies with single statements or blocks of statements. Complex expressions involving multiple variables can also be used within the components of for loops.

Uploaded by

barnabas
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 8

UNIT -7 : Loops

In this unit you’ll learn a very important feature of the C language—looping.

Looping, also called iteration, is used in programming to perform the same


set of statements over and over until certain specified conditions are met.

Three statements in C are designed for looping:

• The while statement


• The do-while statement
• The for statement

The following sections explore these statements.

The while Loop

The purpose of the while keyword is to repeatedly execute a statement over and over
while a given condition is true. When the condition of the while loop is no longer logically true,
the loop terminates and program execution resumes at the next statement following the loop.

The general form of the while statement is

while (expression)
statement;

Here expression is the condition of the while statement. This expression is evaluated
first. If the expression evaluates to a nonzero value, then statement is executed. After
that, expression is evaluated once again. The statement is then executed one more time if the
expression still evaluates to a nonzero value. This process is repeated over and over until
expression evaluates to zero, or logical false.

The idea is that the code inside the loop, (statement; above) will eventually cause
expression to be logically false the next time it is evaluated, thus terminating the loop.
Of course, you often want to use a while keyword to control looping over several statements.

When this is the case, use a statement block surrounded by braces { and }. Each
time the while expression is evaluated, the entire statement block will be executed if the
expression evaluates as true.

Now, let’s look at an example of using the while statement. The program in listing 7.1
uses a while loop to continually read, and then display, character input while the character input
does not equal ‘x’.

1: /* Using a while loop */


2: #include <stdio.h>
3:
4: main()
5: {
6: int c;
7:
8: c = ‘ ‘;
9: printf(“Enter a character:\n(enter x to exit)\n”);
10: while (c != ‘x’) {
11: c = getc(stdin);
12: putchar(c);
13: }
14: printf(“\nOut of the while loop. Bye!\n”);
15: return 0;
16: }

The following is a copy of the output from my computer’s screen. (Note that the characters I
entered are in bold.)
Enter a character:
(enter x to exit)
H
H
i
i
x
x
Out of the while loop. Bye!

As you can see in the output, the program prints back every character that is
typed in, and then stops after x. Line 8 sets the variable c to the value ‘ ‘ (a space character).
This is known as initializing the variable, and we just need to initialize it to something other than
‘x’.

Line 10 is the while statement. The condition inside the parentheses, c != ‘x’, means
the loop will continue executing over and over until c is actually equal to ‘x’. Since we
had just initialized c to equal the ‘ ‘ character, the relation c != x is of course true.
Following the closing parenthesis is an opening brace, so the loop will execute until a
closing brace is encountered.

Line 11 and line 12 read a character and print it back out, and in doing so assign the
character’s value to the variable c. Line 13 is the closing brace, so the loop is done and
execution goes back to line 10, the while statement. If the character that was typed is anything
other than “x” the loop will continue; otherwise, c != x will be logically false, and execution goes
to the next statement after the closing brace at line 13. In this case it moves on to the printf()
call at line 14.

The do-while Loop


In the while statement that we’ve seen, the conditional expression is set at the very top of the
loop. However, in this section, you’re going to see another statement used for looping, do-while,
which puts the expression at the bottom of the loop. In this way, the statements in the loop are
guaranteed to be executed at least once before the expression is tested. Note that statements
in a while loop are not executed at all if the conditional expression evaluates to zero the first
time through.

The general form for the do-while statement is

do {
statement1;
statement2;
.
.
.
} while (expression);

Here, the statements inside the statement block are executed once, and then expression is
evaluated in order to determine whether the looping is to continue. If the expression evaluates
to a nonzero value, the do-while loop continues; otherwise, the looping stops and execution
proceeds to the next statement following the loop.

Note that the do-while statement ends with a semicolon, which is an important distinction from
the if and while statements.

The program below displays the characters A through G by using a do-while loop
to repeat the printing and adding.

1: /*: Using a do-while loop */


2: #include <stdio.h>
3:
4: main()
5: {
6: int i;
7:
8: i = 65;
9: do {
10: printf(“The numeric value of %c is %d.\n”, i, i);
11: i++;
12: } while (i<72);
13: return 0;
14: }

After running the executable file, I have the characters A through G,


along with their numeric values, shown on the screen as follows:

The numeric value of A is 65.


The numeric value of B is 66.
The numeric value of C is 67.
The numeric value of D is 68.
The numeric value of E is 69.
The numeric value of F is 70.
The numeric value of G is 71.

The statement in line 8 of Listing 7.6 initializes the integer variable i with 65.
The integer variable was declared in line 6. Lines 9–12 contain the do-while loop. The
expression i<72 is at the bottom of the loop in line 12. When the loop first starts, the two
statements in lines 10 and 11 are executed before the expression is evaluated. Because the
integer variable i contains the initial value of 65, the printf() function in line 10 displays the
numeric value as well as the corresponding character A on the screen. After the integer variable
i is increased by 1 in line 11, the program control reaches the bottom of the do-while loop. Then
the expression i<72 is evaluated. If the relationship in the expression still holds, the program
control jumps up to the top of the do-while loop, and then the process is repeated. When the
expression evaluates to 0 after i is increased to 72 (i then equals 72 and is therefore not less
than 72), the do-while loop is terminated immediately.

Looping Under the for Statement

The general form of the for statement is

for (expression1; expression2; expression3) {


statement;
}
or
for (expression1; expression2; expression3) {
statement1;
statement2;
.
.
.
}

You see from this example that the for statement uses three expressions (expression1,
expression2, and expression3) that are separated by semicolons.

A for loop can control just one statement as in the first example, or several statements, such as
statement1 and statement2, placed within the braces ({ and }).
The first time the for statement is executed, it first evaluates expression1, which is typically
used to initialize one or more variables.

The second expression, expression2, acts in the same way as the conditional
expression of a do or do-while loop. This second expression is evaluated immediately
after expression1, and then later is evaluated again after each successful looping by the for
statement. If expression2 evaluates to a nonzero (logical true) value, the statements within the
braces are executed. Otherwise the looping is stopped and the execution resumes at the next
statement after the loop.

The third expression in the for statement, expression3, is not evaluated when the for
statement is first encountered. However, expression3 is evaluated after each looping and
before the statement goes back to test expression2 again.

The Null Statement

As you may notice, the for statement does not end with a semicolon. The for statement
has within it either a statement block that ends with the closing brace (}), or a single
statement that ends with a semicolon. The following for statement contains a single
statement:

for (i=0; i<8; i++)


sum += i;

Note that the braces ({ and }) are discarded because the for statement only contains one
statement.

Now let us consider a statement like this:


for (i=0; i<8; i++);

Here the for statement is followed by a semicolon immediately. In the C language, there is a
special statement called the null statement. A null statement
contains nothing but a semicolon. In other words, a null statement is a statement with no
expression.

Therefore, when you review the statement for (i=0; i<8; i++);, you can see that it is
actually a for statement with a null statement. In other words, you can rewrite it as

for (i=0; i<8; i++)


;

Because the null statement has no expression, the for statement actually does nothing but loop.
You’ll see some examples using the null statement with the for statement later.

Just remember that the do-while loop is the only looping statement that uses a semicolon
immediately after it as part of its syntax. The while and for statements are followed immediately
by a loop, which could be a single statement followed by a
semicolon, a statement block which has no semicolon afterwards, or just a semicolon
(null statement) by itself.

Using Complex Expressions in a for Statement


The C language allows you to use the comma operator to combine multiple expressions into the
three parts of the for statement.

For instance, the following form is valid in C:


for (i=0, j=10; i!=j; i++, j--){
/* statement block */
}

Here, in the first expression, the two integer variables i and j are initialized, respectively, with 0
and 10 when the for statement is first encountered. Then, in the second field, the relational
expressions i!=j is evaluated and tested. If it evaluates to zero (false), the loop is terminated.
After each iteration of the loop, i is increased by 1 and j is reduced by 1 in the third expression.
Then the expression i!=j is evaluated to determine whether or not to execute the loop again.

Now, let’s look at a real program.

1: /* Multiple expressions */
2: #include <stdio.h>
3:
4: main()
5: {
6: int i, j;
7:
8: for (i=0, j=8; i<8; i++, j--)
9: printf(“%d + %d = %d\n”, i, j, i+j);
10: return 0;
11: }

I get the following output displayed on the screen after running the executable file,

0+8=8
1+7=8
2+6=8
3+5=8
4+4=8
5+3=8
6+2=8
7+1=8

Line 6 declares two integer variables, i and j, which are used in a


for loop. In line 8, i is initialized with 0 and j is set to 8 in the first expression of the for statement.
The second expression contains a condition, i < 8, which tells the computer to keep looping as
long as the value of i is less than 8.

Each time, after the statement controlled by for in line 9 is executed, the third expression is
evaluated, causing i is increase (increment) by 1 while j is reduced
(decremented) by 1. Because there is only one statement inside the for loop, no braces
({ and }) are used to form a statement block.
The statement in line 9 displays the addition of i and j on the screen during the looping, which
outputs eight results during the looping by adding the values of the two variables, i and j.

Adding multiple expressions into the for statement is a very convenient way to manipulate more
than one variable in a loop.

Using Nested Loops

It’s often necessary to create a loop even when you are already in a loop. You can put a loop
(an inner loop) inside another one (an outer loop) to make nested loops. When the program
reaches an inner loop, it will run just like any other statement inside the outer loop.

The program below is an example of how nested loops work.

1: /* Demonstrating nested loops */


2: #include <stdio.h>
3:
4: main()
5: {
6: int i, j;
7:
8: for (i=1; i<=3; i++) { /* outer loop */
9: printf(“The start of iteration %d of the outer loop.\n”, i);
10: for (j=1; j<=4; j++) /* inner loop */
11: printf(“ Iteration %d of the inner loop.\n”, j);
12: printf(“The end of iteration %d of the outer loop.\n”, i);
13: }
14: return 0;
15: }

The following result is obtained by running the executable file:

The start of iteration 1 of the outer loop.


Iteration 1 of the inner loop.
Iteration 2 of the inner loop.
Iteration 3 of the inner loop.
Iteration 4 of the inner loop.
The end of iteration 1 of the outer loop.
The start of iteration 2 of the outer loop.
Iteration 1 of the inner loop.
Iteration 2 of the inner loop.
Iteration 3 of the inner loop.
Iteration 4 of the inner loop.
The end of iteration 2 of the outer loop.
The start of iteration 3 of the outer loop.
Iteration 1 of the inner loop.
Iteration 2 of the inner loop.
Iteration 3 of the inner loop.
Iteration 4 of the inner loop.
The end of iteration 3 of the outer loop.
In the above program, two for loops are nested together. The outer for loop starts in
line 8 and ends in line 13, while the inner for loop starts in line 10 and ends in
line 11. The inner loop is only one statement that prints out the iteration number according to
the numeric value of the integer variable j. As you see in line 10, j is initialized with 1, and is
increased by 1 after each looping (that is, iteration). The execution of the inner loop stops when
the value of j is greater than 4. Besides the inner loop, the outer loop has two statements in
lines 9 and 12, respectively.

The printf() function in line 9 displays a message showing the beginning of an iteration
from the outer loop. An ending message is sent out in line 12 to show the end of the
iteration from the outer loop.

From the output, you can see that the inner loop is finished before the outer loop starts another
iteration. When the outer loop begins another iteration, the inner loop is encountered and run
again. The output from the program in clearly shows the execution orders of the inner and outer
loops.

You might also like