for Loop


Pinky: How many more loops do we have Brain?

Brain: We only have one more. The for loop.

Pinky: Does the for loop have a flowchart?

Brain: Yes it does. Here it is:

Pinky: Hey, Brain, I'm just not seeing it. The other loops made sense. This one doesn't.

Brain: Well, that's because the name of this loop doesn't imply what it does. However, it saves a lot of work most of the time.

Pinky: Do you think that you could figure this one out because I'm just lost?

Brain: Sure.

loop3.txt

Brain: The for loop is different from the other loops and control statements because if you don't know how it flows, there is absolutely no way to figure out what is going to happen. Now to the program. The program starts out, but does not have to declare and initialize a variable. Then we go to the for loop. In every for loop statement there are three C++ statements separated by two semi-colons(;). They can be anything, but to make the for statement logical, the first one declares and initializes a variable. The second statement is the test statement which tests the variable that was declared in the first statement. The program only executes the piece of code if this statement is true. The last statement is another valid C++ statement. It increments the variable declared in the first statement. So in this program on line 10 we declare and initialize control to 0. The program then checks to make sure that the value of control is less than 10. The program executes the piece of code and then goes back up to line 10, increments control, and tests it again before it can execute the piece of code again. It increments, tests and executes until the tests no longer produce a true result.

Pinky: That's confusing. Why did the people who made C++ do that?

Brain: Well, if you think about it, Pinky, in the other loop that we just looked at, do...while, and while, we had to declare and initialize a variable outside of the loop, and the last line in our piece of code was to increment the control variable. The for loop makes all of this easier to read by putting the initialization, test, and increment all at the top of the loop.

Pinky: That makes sense. Couldn't we still use do...while and while?

Brain: Yes, most of the time it makes no difference which loop you use, but every once in a while there will be only one certain loop that will complete the task properly. Also, even if you personally don't like using for you should at least become familiar with it because it is used in a lot of the programs we will be seeing later.

The following is a link to a clean-up page. It tells about some of the small things in C++ that don't really go in any section, but are very important. click me. Or you can go straight onto fuctions.

[Home] [Next Section] [Back]