The For Repetition Structure Syntax for initialexpression 1

















- Slides: 17
The For Repetition Structure
Syntax for (initial-expression 1, conditional-expression 2, loop-expression 3) { statement(s); } Example: for (int counter=1; counter <= 10; counter++; ) cout << counter << endl;
What the for Loop Looks Like: The C++ for loop contains four major parts: 1. The value at which the loop starts. 2. The condition under which the loop is to continue. 3. The changes that are to take place for each loop. 4. The loop instructions.
Components of a typical for loop. For Keyword Control Variable Final value of control variable Name for (int counter = 1; counter <= 10; counter++) initial value Loop increment of control variable continuation condition of control variable
Flowchart Counter = 1 True Counter <= 10 False cout << counter <<endl; Body of loop counter++; Increment the counter variable
Example Program #include <iostream. h> main() { int time; // Counter variable. // The loop starts here. for(time = 1; time <= 5; time = time + 1) cout << "Value of time = " << time << "n"; // The loop stops here. cout << "This is the end of the loop. n"; }
More Than One Statement You can have more than one statement in a C++ for loop. By using • the open braces { to indicate the beginning of the loop • the close braces } to indicate the end of the loop.
Example Program: This program computes the distance a body falls in feet per second, for the first 5 seconds of free fall as given by the equation: s = ½ at 2 Where s = the distance in feet. a = acceleration due to gravity t = time in seconds
#include <iostream. h> #define a 32. 0 main() { int time; // Counter variable. int distance; // Distance covered by the falling // body.
// The loop starts here. for(time = 1; time <= 5; time = time + 1) { distance = 0. 5 * a * time; cout << "Distance at the end of " << time << " seconds is "; cout << distance << " feet. n"; } // The loop stops here.
cout << "This is the end of the loop. n"; }
Your output should look like:
The Increment and Decrement Operators Operator Meaning X++ Increment X after any operation with it. (called post-incrementing). ++X Increment X before any operation with it. (called pre-incrementing). X-- Decrement X after any operation with it. (called post-decrementing). ++X decrement X before any operation with it. (called pre-decrementing).
#include <iostream. h> main() { int count; int number 1 = 0; int number 2 = 0; // Program counter. // Number to post-increment. // Number to pre-increment. for(count = 1; count <= 5; count++) { cout << "Post-incrementing number = " << number 1++ << ", "; cout << "Pre-incrementing number = "<< ++number 2 << "n"; } }
Your program should look like:
For Today: For Loop Worksheet Homework: Read pages 87 to 95. Quiz on Friday regarding For Loops!