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

(Romina) #1

15. Looking for Another Way to Create Loops


In This Chapter


  • Looking for another way to repeat code

  • Working with for


Another type of C loop is called the for loop. A for loop offers more control than while and do-
while. With a for loop, you can specify exactly how many times you want to loop; with while
loops, you must continue looping as long as a condition is true.


C programs have room for all three kinds of loops. Sometimes one loop fits one program’s
requirements better than another. For example, if you wrote a program to handle customer orders as
customers purchase items from the inventory, you would need to use a while loop. The program
would process orders while customers came through the door. If 100 customers happened to buy
things, the while loop would run 100 times. At the end of the day, you might want to add the 100
customer purchases to get a total for the day. You could then use a for loop because you would then
know exactly how many times to loop.


Note

By incrementing counter variables, you can simulate a for loop with a while loop.
You also can simulate a while with a for! Therefore, the kind of loop you use
ultimately depends on which kind you feel comfortable with at the time.

for Repeat’s Sake!


As you can see from the lame title of this section, the for loop is important for controlling repeating
sections of code. The format of for is a little strange:


Click here to view code image


for (startExpression; testExpression; countExpression)
{ block of one or more C statements; }

Perhaps a short example with actual code is easier to understand:


Click here to view code image


for (ctr = 1; ctr <= 5; ctr++)
{
printf("Counter is at %d.\n", ctr);
}

If you are looking at the code and thinking that it’s a bit familiar, you are right. This code would be
the beginning of a fifth version of the count up/count down program, but one that used a for loop
instead. Here’s how this for statement works: When the for begins, the startExpression,

Free download pdf