The For Repetition Structure
Syntaxfor (initial-expression1, conditional-expression2, loop-expression3)
{ 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 Control Final value
Keyword Variable of control variable
Name
for (int counter = 1; counter <= 10; counter++)
initial value Loop increment
of control continuation of control
variable condition variable
Flowchart
Counter = 1
Counter <= 10 cout << counter <<endl;
counter++;
False
True
Body of loop 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 = ½ at2
Wheres = 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 * 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 MeaningX++ 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; // Program counter.int number1 = 0; // Number to post-increment.int number2 = 0; // Number to pre-increment.
for(count = 1; count <= 5; count++){
cout << "Post-incrementing number = " << number1++ << ", ";
cout << "Pre-incrementing number = "<< ++number2 << "\n";}
}
Your program should look like:
For Today:
For Loop Worksheet
Homework:
Read pages 87 to 95.
Quiz on Friday regarding For Loops!