Sams Teach Yourself C in 24 Hours (23 page)

BOOK: Sams Teach Yourself C in 24 Hours
12.89Mb size Format: txt, pdf, ePub
ads

In other words, when the for loop is first encountered, i is set to 0, the expression i<16

is evaluated and found to be true, and therefore the statements within the body of the for loop are executed. Following execution of the for loop, the third expression i++ is executed incrementing i to 1, and i<16 is again evaluated and found to be true, thus the body of the loop is executed again. The looping lasts until the conditional expression i<16 is no longer true.

There is only one statement inside the for statement body, as you can see in line 10. The statement contains the printf() function, which is used to display the hex numbers (both uppercase and lowercase) converted from the decimal values by using the format specifiers, %X and %x.

The decimal value is provided by the integer variable i. As explained earlier, i contains the initial value of 0 right before and during the first looping. After each looping, i is increased by 1 because of the third expression, i++, in the for statement. The last value provided by i is 15. When i reaches 16, the relation indicated by the second expression, 10 067231861x CH07 4.10.2000 11:01 AM Page 112

112

Hour 7

i<16, is no longer true. Therefore, the looping is stopped and the execution of the for statement is completed.

Then, the statement in line 12 returns 0 to indicate a normal termination of the program, and finally, the main() function ends and returns the control back to the operating system.

As you see, with the for statement you can write a very concise program. In fact, the program in Listing 7.3 is more than 10 lines shorter than the one in Listing 5.5, although the two programs end up doing exactly the same thing.

Actually, you can make the program in Listing 7.3 even shorter by discarding the braces ({ and }) since there is only one statement inside the statement block.

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 in the book.

10 067231861x CH07 4.10.2000 11:01 AM Page 113

Working with Loops

113

Because the null statement is perfectly legal in C, you should pay attention to placing semicolons in your for statements. For example, suppose you

intended to write a for loop like this:

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

sum += i;

If you accidentally put a semicolon at the end of the for statement like this, however,

7

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

sum += i;

your C compiler will still accept it, but the results from the two for statements will be quite different. (See exercise 1 in this lesson for an example.) 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. Listing 7.4 shows an example of using multiple expressions in the for statement.

10 067231861x CH07 4.10.2000 11:01 AM Page 114

114

Hour 7

TYPE

LISTING 7.4

Adding Multiple Expressions to the for Statement

1: /* 07L04.c: Multiple expressions */

2: #include

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, 07L04.exe:

0 + 8 = 8

OUTPUT

1 + 7 = 8

2 + 6 = 8

3 + 5 = 8

4 + 4 = 8

5 + 3 = 8

6 + 2 = 8

7 + 1 = 8

In Listing 7.4, line 6 declares two integer variables, i and j, which are used in a
ANALYSIS
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. To learn more about using multiple expressions in a for loop, look at the example in Listing 7.5.

10 067231861x CH07 4.10.2000 11:01 AM Page 115

Working with Loops

115

LISTING 7.5

Another Example of Using Multiple Expressions in the

TYPE

for Statement

1: /* 07L05.c: Another example of multiple expressions */

2: #include

3:

4: main()

5: {

6: int i, j;

7:

7

8: for (i=0, j=1; i<8; i++, j++)

9: printf(“%d - %d = %d\n”, j, i, j - i);

10: return 0;

11: }

The following output is displayed on the screen after the executable 07L05.exe is run on my machine:

1 - 0 = 1

OUTPUT

2 - 1 = 1

3 - 2 = 1

4 - 3 = 1

5 - 4 = 1

6 - 5 = 1

7 - 6 = 1

8 - 7 = 1

In the program shown in Listing 7.5, two integer variables, i and j, are declared
ANALYSIS
in line 6.

Note that in line 8, there are two assignment expressions, i=0 and j=1, in the first expression of the for statement. These two assignment expressions initialize the i and j integer variables, respectively.

There is one relational expression, i<8, in the second field, which is the condition that has to be met before the looping can be carried out. Because i starts at 0 and is incremented by 1 after each loop, there are total of 8 loops that will be performed by the for statement.

The third expression contains two expressions, i++ and j++, that increase the two integer variables by 1 each time after the statement in line 9 is executed.

The printf() function in line 9 displays the subtraction of the two integer variables, j and i, within the for loop. Because there is only one statement in the statement block, the braces ({ and }) are not needed.

10 067231861x CH07 4.10.2000 11:01 AM Page 116

116

Hour 7

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.

Listing 7.6 is an example of how nested loops work.

TYPE

LISTING 7.6

Using Nested Loops

1: /* 07L06.c: Demonstrating nested loops */

2: #include

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 07L06.exe: The start of iteration 1 of the outer loop.

OUTPUT

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.

10 067231861x CH07 4.10.2000 11:01 AM Page 117

Working with Loops

117

In Listing 7.6, two for loops are nested together. The outer for loop starts in
ANALYSIS
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.

7

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 Listing 7.6 clearly shows the execution orders of the inner and outer loops.

Don’t confuse the two relational operators (< and <=) and misuse them in the expressions of loops.

For instance, the following

for (j=1; j<10; j++){

/* statement block */

}

means if j is less than 10, keep looping. Thus, the total number of iterations is 9. However, in the following example,

for (j=1; j<=10; j++){

/* statement block */

}

the total number of iterations is 10 because the relational expression j<=10

is evaluated in this case. Note that the expression evaluates to 1 (logical true) as long as j is less than or equal to 10.

Therefore, you see the difference between the operators < and <= causes the looping in the first example to be one iteration shorter than the looping in the second example.

10 067231861x CH07 4.10.2000 11:01 AM Page 118

118

Hour 7

Summary

In this lesson you learned the following important concepts and statements:

• Looping can be used to perform the same set of statements over and over until specified conditions are met.

• Looping makes your program more concise.

• There are three statements, while, and do-while, and for, that are used for looping in C.

• The while statement contains one expression, which is the conditional expression which controls the loop.

• The while statement does not end with a semicolon.

• The do-while statement places its conditional expression at the bottom of the loop.

• The do-while statement ends with a semicolon.

• There are three expressions in the for statement. The second expression is the conditional expression.

• The for statement does not end with a semicolon.

• Multiple expressions, combined via commas, can be used as one expression in the for statement.

• In a nested loop, inner loop finishes before the outer loop resumes its iteration in nested loops.

In the next lesson you’ll learn about more operators used in the C language.

Q&A

Q What is the difference between the
while
and
do-while
statements?

A
The main difference is that in the while statement, the conditional expression is evaluated at the top of the loop, while in the do-while statement, the conditional expression is evaluated at the bottom of the loop. Therefore, the statements controlled by the do-while statement are guaranteed to be executed at least once whereas the loop in a while statement may never be executed at all.

BOOK: Sams Teach Yourself C in 24 Hours
12.89Mb size Format: txt, pdf, ePub
ads

Other books

The Reluctant Countess by Wendy Vella
Flaw by Magdalena Tulli
Pretty Ugly: A Novel by Kirker Butler
The Black Hawk by Joanna Bourne
It's All About Him by Colette Caddle
The Darkest Secret by Gena Showalter
Esperanza Rising by Pam Muñoz Ryan


readsbookonline.com Copyright 2016 - 2024