3.3. For LoopsΒΆ

Even though while type of construct is very useful in a wide variety of situations, another iterative structure, the for statement, can be used to iterate across a range of values easily. However, you must first find the length of your container. For vectors, you can simply call the .length() function. For arrays, the number of elements can be found by getting the size in memory of the array by using the sizeof() function, and then dividing it by the size of the first element of the array using the same sizeof() function. Because all elements in C++ arrays are the same type, they take the same amount of space and that can be used to find the number of elements the Array contains!

An optional secondary version of the for loop has been commented out of the above code. You can try running this in your version of C++ to see if it works, but in some older versions of C++, such as C++98, it does not.

The above loop assigns the variable index to be each successive value from 0 to numsSize.
Then, the value at that index in the array is printed to the console.

A common use of the for statement is to implement definite iteration over a range of values. The statement

will perform the print function five times. The range function will return a range object representing the sequence 0,1,2,3,4 and each value will be assigned to the variable item. This value is then squared and printed.

The other very useful version of this iteration structure is used to process each character of a string. The following code fragment iterates over a list of strings and for each string processes each character by appending it to a list. The result is a list of all the letters in all of the words.

Next Section - 3.4. Summary