More on the <I>for</I> Loop


Let's show you some examples of the for loop. Let's say you had an array of ten integers, and you wanted to assign 500 to each integer. You could ten assignment statements, but it's easier just to say:

for (i = 0; i < 10 ; i = i + 1) {
  taco[i] = 500;
}

First, in the initializing statement is executed, and i is set to 0. Then, the loop begins, each time incremented by 1. First, the statement is "taco[0] = 500", then the next time through it's "taco[1] = 500", then "taco[2] = 500", and so on, until it has looped ten times. At that point, when i is set to 10, it checks the statement "i < 10". Since 10 isn't less-than 10, the statement is FALSE, and the for loop exits.

Let's say we had two arrays of 50 integers, burrito and salsa, that we wanted to add together into a third array, chimichanga. Since it's alot of repetition, it's the perfect candidate for a for loop! Look at the code below:

for (i = 0 ; i < 50 ; i = i + 1) {
  chimichanga[i] = burrito[i] + salsa[i];
}

This is much easier than writing out:

chimichanga[0] = burrito[0] + salsa[0];
chimichanga[1] = burrito[1] + salsa[1];
chimichanga[2] = burrito[2] + salsa[2];
...

And so on, 50 times!

Hopefully you understand how the for loop works now. If you're still a little confused, please, experiment on your own. If you're still having problems, just remember the form:

int i;

for (i = (START VALUE) ; i < (END VALUE) ; i = i + 1) {
   (LOOP)
}

Which will loop i from (START VALUE) to (END VALUE), each time executing (LOOP).


Table of Contents

The Big Picture | Comments | Variables | More on Variables
Variable Operations | Making Choices | More on if | Using else
Using switch | The while Loop | The do..while Loop | Constants
The for Loop | More on the for Loop | Exercises