For Loops
See pages 209-211 in A Computer Science Tapestry for more information on for loops, and page 218 about formatted output.
While loops are useful for many situations, such as the outer loop in the last assignment which kept track of distance travelled. In that situation the commands were repeated for an unknown number of times. When loops are repeated a known number of times (such as the inner loops on the previous program which were repeated six times each), it is more common to use for loops. We were introduced to for loops in Visual Basic where they were known as for-next loops. In C++ the format of for loops is as follows:
The initialization statement occurs the first time through the loop. The test expression is checked each time through the loop. If it is satisfied, the loop continues. The update statement happens once each time through the loop and is usually in the form of an increasing counter. Taking this information we can write a for loop to count off the numbers between one and nine as shown here:
int i;
Compare this to the while loop that does the same thing. This demonstrates that while loops and for loops can perform similar functions. The format of the for loop is easier to read however, when it is used to count off a known number of times. That is, you can easily read the above for loop and see that it counts from one to nine. The while loop that does the same thing is less obvious.
Formatted Output
It is sometimes necessary to have numbers that are output line up. For example if you wanted to ouput the following table:
1 2 3 4 5
2 4 6 8 10
3 6 9 12 15
4 8 12 16 20
5 10 15 20 25
You could to this by checking the length of each number output and printing the necessary number of spaces to make the numbers line up, but that would be a lot of work. Instead of this you can use the field width statement. This statement will make sure that a number takes up a certain number of spaces, if the number is too short, it will add the appropriate number of blank spaces. For example the statement cout.width(4) followed by the command cout<<12 will output two spaces and then the number 12, so that is takes up 4 spaces total. If instead the statement cout.width(4) was followed by the command cout<<123, one space followed by the number 123 would be output.
An Exercise in For Loops and Formatted Output
As a brief exercise, take the information that you have learned here on for loops and formatted output and create a program that will output a multiplication table. The program should take as input four numbers- a low and high number along the x-axis and a low and high number along the y-axis. You should have the program output the result of multiplying each pair of numbers over the entire range. For example:
2 3 4 5
3 6 9 12 15
4 8 12 16 20
5 10 15 20 25
6 12 18 24 30
Click Here to Download a DOS
Version of the Program
Be sure that you make use of for loops and formatted output.