08.01.2023 Views

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

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Chapter 5 ■ Programs with Repetition Logic

• h is set to first and the body is executed

• 1 is added to h; if the value of h is less than or equal to last, the body is

executed again

• 1 is added to h; if the value of h is less than or equal to last, the body is

executed again

• and so on

When the value of h reaches last, the body is executed for the last time and control goes to

the statement, if any, after endfor.

The net effect is that the body is executed for each value of h between first and last,

inclusive.

5.11.1 The for Statement in C

The pseudocode construct

for h = 1 to 5 do

print "I must not sleep in class"

endfor

is implemented in C as follows:

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

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

assuming that h is declared as int. However, it is more common to declare h in the for statement

itself, like this:

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

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

In this case, though, note that the scope of h extends only to the body of the for (see next).

■■Caution The ability to declare the loop variable in the for statement was not allowed in early versions of C.

If you are using an older compiler, you will get an error. In that case, just declare the loop variable before the for

statement.

In C, the body of the for must be a single statement or a block. In the example, it is the single

printf statement. If it were a block, we would write it in the following form:

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

<statement1>

<statement2>

etc.

}

120

www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!