97
Note the following:
for (i=0; i<10; i++)
printf(…)
This tells the computer to execute the printf() statement starting from a count of 0
which is incremented by 1 which each pass of the loop, until the count reaches 10.
As with the “if” and “while” loops, multiple statements within a “for” loop are enclosed
in braces.
Let’s write a program that squares all of the integer from 1 to 100.
/* 100 squares */
/* #include <stdio.h> */
main()
{
int i;
for (i=1; i<=100; i++)
printf(“%8d %8d¥n”,i,i*i);
getchar(); /* waits ret key */
}
First, let’s look at the expressions contained in the parentheses following the “for”
statement and see what each of them mean.
•
Expression 1
i=1
Initial value of counter is 1.
•
Expression 2
i<=100
Repeat as long as I is less than or equal to 100.
•
Expression 3
i++
Increment I by 1 with each pass of loop (i=i+1).
In effect, this tells the computer to keep repeating the loop starting with a counter
value of 1, and repeat the loop as long as the counter value is 100 or less.
In the next line, the “%8d” in the first argument tells the computer to display the
decimal value flush right in an 8-character block reserved on the display. Flush left
would be “%-8d”.
When you execute this program, the following result should be produced:
1 1
2 4 …
… 100 10000
>_
The following shows how the same loop could be written as a “for” loop and a “while”
loop. As you can see, the “for” loop is much easier to write and read.
For (expression 1; expression 2; expression 3)
Statement
⇑
⇓
expression 1;
while (expression 2)
{
Statement
expression 3
}