Read Sams Teach Yourself C in 24 Hours Online
Authors: Tony. Zhang
5. The following program is supposed to compare the two variables, x and y, for equality. What’s wrong with the program? (Hint: Run the program to see what it prints out.)
#include
main()
{
int x, y;
x = y = 0;
printf(“The comparison result is: %d\n”, x = y);
return 0;
}
10 067231861x CH07 4.10.2000 11:01 AM Page 105
HOUR 7
Working with Loops
Heaven and earth:
Unheard sutra chanting
Repeated…
—Zen saying
In the previous lessons, you learned the basics of the C program, several important C functions, standard I/O, and some useful operators. In this lesson 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.
10 067231861x CH07 4.10.2000 11:01 AM Page 106
106
Hour 7
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’.
TYPE
LISTING 7.1
Using a while Loop
1: /* 07L01.c: Using a while loop */
2: #include
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: }
10 067231861x CH07 4.10.2000 11:01 AM Page 107
Working with Loops
107
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:
OUTPUT
(enter x to exit)
H
H
i
i
x
7
x
Out of the while loop. Bye!
As you can see in the output, the program prints back every character that is
ANALYSIS
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.
10 067231861x CH07 4.10.2000 11:01 AM Page 108
108
Hour 7
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 in Listing 7.2 displays the characters A through G by using a do-while loop to repeat the printing and adding.
TYPE
LISTING 7.2
Using a do-while Loop
1: /* 07L02.c: Using a do-while loop */
2: #include
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 07L02.exe of Listing 7.6, 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.
OUTPUT
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.
10 067231861x CH07 4.10.2000 11:01 AM Page 109
Working with Loops
109
The statement in line 8 of Listing 7.6 initializes the integer variable i with 65.
ANALYSIS
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.
7
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 10 067231861x CH07 4.10.2000 11:01 AM Page 110
110
Hour 7
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.
In Hour 5, “Handling Standard Input and Output,” you saw an example (Listing 5.5) that converts the decimal numbers 0 through 15 into hex numbers. Back then, the conversions had to be written in separate statements. Now, with the for statement, you can rewrite the program in Listing 5.5 in a very efficient way. Listing 7.3 shows the rewritten version of the program.
TYPE
LISTING 7.3
Converting 0 through 15 to Hex Numbers
1: /* 07L03.c: Converting 0 through 15 to hex numbers */
2: #include
3:
4: main()
5: {
6: int i;
7:
8: printf(“Hex(uppercase) Hex(lowercase) Decimal\n”);
9: for (i=0; i<16; i++){
10: printf(“%X %x %d\n”, i, i, i);
11: }
12: return 0;
13: }
After creating the executable file 07L03.exe, I obtain the following output by running 07L03.exe. (The output is in fact the same as the one from 05L05.exe in Hour 5.) Hex(uppercase) Hex(lowercase) Decimal
OUTPUT
0 0 0
1 1 1
2 2 2
3 3 3
4 4 4
5 5 5
6 6 6
7 7 7
8 8 8
9 9 9
A a 10
B b 11
10 067231861x CH07 4.10.2000 11:01 AM Page 111
Working with Loops
111
C c 12
D d 13
E e 14
F f 15
Now, let’s have a look at the code in Listing 7.3. As you know, line 2 includes
ANALYSIS
the header file stdio.h for the printf() function used later in the program.
Inside the body of the main() function, the statement in line 6 declares an integer vari-7
able, i. Line 8 displays the headline of the output on the screen.
Lines 9–11 contain the for statement. Note that the first expression in the for statement is i = 0, which is an assignment expression that initializes the integer variable i to 0.
The second expression in the for statement is i < 16, which is a relational expression.
This expression evaluates to nonzero (true) as long as the relation indicated by the less-than operator (<) holds. As mentioned earlier, the second expression is evaluated by the for statement each time after a successful looping. If the value of i is less than 16, which means the relational expression remains true, the for statement will start another loop. Otherwise, it will stop looping and exit.
The third expression in the for statement is i++. When this expression is evaluated, the integer variable i is increased by 1. This is done after each statement inside the body of the for statement is executed. Here it doesn’t make a big difference whether the post-increment operator (i++) or the pre-increment operator (++i) is used in the third expression.