From the course: Learning C++

Unlock the full course today

Join today to access over 24,700 courses taught by industry experts.

For loops

For loops

- [Instructor] For loops are traditionally used when you know the range to traverse in advance. The first and last iterations are normally specified in the loop statement. Well, for loops in C and C++ are extremely flexible. A for loop has a directly equivalent implementation with a while loop. In this example, I'll calculate the average of the elements in the same vector we saw in the while loop example. That's why we have a float definition for the average in line 10. Let me start in line 12 by initializing the average to zero. Now the for loop syntax has three parts separated by semicolons. First we have the initialization statement, then the condition, and lastly, the increment expression. So let me go to line 13 and type "for." The first part is the initialization of the iterating variable, and you may declare that variable in this part. So it will belong to the scope of the body of the loop. It will be an integer…

Contents