C Programming Absolute Beginner's Guide (3rd Edition)

(Romina) #1
}

Here is the output of this code:


Counter is at 1.
Counter is at 2.
Counter is at 3.
Counter is at 4.
Counter is at 5.

Tip

If you follow Figure 15.1’s guiding line and read the preceding while loop, you’ll
see that the for and while do the same thing. The ctr = 1; that precedes the
while is the first statement executed in the for.

A do-while loop can’t really represent the for loop because the relational test is performed
before the body of the for loop and after it in the do-while. As you might recall from the end of
Chapter 14, “Code Repeat—Using Loops to Save Time and Effort,” the do-while test always
resides at the bottom of the loop.


Working with for


The for loop reads a lot like the way you speak in everyday life. Consider this statement:


For each of our 45 employees, calculate the pay and print a check.


This statement leaves no room for ambiguity. There will be 45 employees, 45 pay calculations, and
45 checks printed. To make this loop work for even more companies, the program could prompt the
user to enter how many employees will need to have payroll calculations and then use that entry for
the loop as follows:


Click here to view code image


printf("How many employees in the organization? ");
scanf(" %d", &employees);
// Loop to calculate payroll for each employee
for (i=1; i <= employees; i++;)
{
// Calculations for each employee follow...

for loops don’t always count up as the preceding two did. This for loop counts down before
printing a message:


Click here to view code image


for (cDown = 10; cDown >0; cDown--)
{
printf("%d.\n", cDown);
}
printf("Blast off!\n");
Free download pdf