CS 102
[Schedule]
[Examples] [Programs]
[Notes & Reference] [Syllabus]
[Lab & TA] [Tests]
[Grades]
The for loop gives us the same functionality as a while loop, with a more convenient way to keep track of loop counting variables. The general format is:
for (initialize; endingCondition; postLoopUpdate) {
action;
}
The initialize code is performed the first time only. Then endingCondition is checked. If it is true, the action(s) inside the loop are exectued. After the code in the loop is executed, the postLoopUpdate code is executed. The endingCondition is again checked, and the code in the loop is again executed, and so on, until the endingCondition is false.
Before studying the following examples, take a look at the example programs describing the use of cin and cout for input and output. The first one is a simple example, and the second one combines cin and cout with scanf and printf.
Consider the following examples, found in the course account at examples/other/multiplication. The first one shows how to display a multiplication list for a single number. For instance, selecting 3 would then display in a column the values 3, 6, 9, 12, 15, 18, ... and so on up to 36, which is 3 times 12. Using a while loop, this looks like:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
// mult1.c - display mult. table from 1 - 12 for a # #include |
(Note: be sure to have looked at the notes on cin and cout before looking at this example.) The equivalent using a for loop instead of a while loop is:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
// mult2.c - display mult. table from 1 - 12 for a # using for #include |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
// mult3.c - display mult. table from start - end for a # #include |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
// mult4.c - display some rows of a mult. table from // firstRow to lastRow, displaying columns // up until the numColumns. #include |
[CS Dept] [UIC]
[Prof. Reed]