Control Sructures - Repetition
Both of the following loops add up all of the numbers between 1 and 50.
// while loop example // loop body runs 50 times, condition checked 51 times int i = 1, sum = 0; while (i cout do/while loop example // loop body runs 50 times, condition checked 50 times int i = 1, sum = 0; do < sum += i; // means: sum = sum + i; i++; // means: i = i + 1; >while (i
Example Links
- A simple while-loop example (controlled by counting)
- Same example, but the while-loop counts backwards
- Another simple while-loop example, this one not controlled by counting
- Similar example, but with a do/while loop (and slightly different control condition).
The for loop
- The for loop is most convenient with counting loops -- i.e. loops that are based on a counting variable, usually a known number of iterations
- Format of for loop:
for (initialCondition; testExpression; iterativeStatement) statement
for (initialCondition; testExpression; iterativeStatement) < statement1; statement2; // . statementN; >
- The initialCondition runs once, at the start of the loop
- The testExpression is checked. (This is just like the expression in a while loop). If it's false, quit. If it's true, then:
- Run the loop body
- Run the iterativeStatement
- Go back to the testExpression step and repeat
Examples of for loops
- Recall this while loop example, which adds the numbers from 1 to 50:
int i = 1, sum = 0; while (i cout
Here's a for loop that does the same job:
// for loop example // loop body runs 50 times, condition checked 51 times int i, sum = 0; for (i = 1; i cout
for (int i = 0; i < 10; i++) cout
So does this one
for (int i = 1; i
- A counting algorithm
- A summing algorithm -- Adding up something with a loop
- A product algorithm -- Multiplying things with a loop
- Simple nested loop example
- Prints out a rectangle
- Prints out a triangle
Special notes about for loops:
- It should be noted that if the control variable is declared inside the for header, it only has scope through the for loop's execution. Once the loop is finished, the variable is out of scope:
for (int counter = 0; counter < 10; counter++) < // loop body >cout
This can be avoided by declaring the control variable before the loop itself.
int counter; // declaration of control variable for (counter = 0; counter < 10; counter++) < // loop body >cout
for (i = 100; i > 0; i--) for (c = 3; c
Special statements: break and continue
- These statements can be used to alter the flow of control in loops, although they are not specifically needed. (Any loop can be made to exit by writing an appropriate test expression).
- break: This causes immediate exit from any loop (as well as from switch blocks)
- In a while or do-while loop, the rest of the loop body is skipped, and execution moves on to the test condition
- In a for loop, the rest of the loop body is skipped, and execution moves on to the iterative statement
- An example of continue