08.01.2023 Views

Learn to Program with C_ Learn to Program using the Popular C Programming Language ( PDFDrive )

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Chapter 5 ■ Programs with Repetition Logic

When a for statement is encountered, it is executed as follows:

1. <expr1> is evaluated.

2. <expr2> is evaluated. If it is false, execution continues with the

statement, if any, after <statement>. If it is true, <statement> is

executed, followed by <expr3>, and this step (2) is repeated.

This can be expressed more concisely as follows:

<expr1>;

while (<expr2>) {

<statement>;

<expr3>;

}

Consider the following:

for (h = 1; h <= 5; h++)

printf("I must not sleep in class\n");

• h = 1 is <expr1>

• h <= 5 is <expr2>

• h++ is <expr3>

• <statement> is printf(...);

This code is executed as follows:

1. h is set to 1

2. The test h <= 5 is performed. It is true, so the body of the loop is executed

(one line is printed). The reinitialization step h++ is then performed, so h

is now 2.

3. The test h <= 5 is again performed. It is true, so the body of the loop is

executed (a second line is printed); h++ is performed, so h is now 3.

4. The test h <= 5 is again performed. It is true, so the body of the loop is

executed (a third line is printed); h++ is performed, so h is now 4.

5. The test h <= 5 is again performed. It is true, so the body of the loop is

executed (a fourth line is printed); h++ is performed, so h is now 5.

6. The test h <= 5 is again performed. It is true, so the body of the loop is

executed (a fifth line is printed); h++ is performed, so h is now 6.

7. The test h <= 5 is again performed. It is now false, so execution of the

for loop ends and the program continues with the statement, if any, after

printf(...).

122

www.it-ebooks.info

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!