Title: For Statement
Course: CPS 120: Introduction to Computer Science ~ Master (Aug/2015) OLD > Section: Learning Units

Visual C++ for statement:

- Is an iterative (definite) statement with an index variable and a condition that tests that variable.  It also has a true path.
- The index variable must be declared – it is usually type int.
- The index variable has starting, ending, and step (incrementing) values.
- At loop start, the index variable is assigned the starting value and the condition is tested.
- Continues to execute the true path while the condition is true.
- After the first loop, the index variable is changed by the step value and the condition is retested.
- Depending on the starting, ending, and step values, the true path may not execute at all.
- Has the form:

Statement part | Description
for | For loop keyword.
index-start | Assignment statement that gives starting value to index variable.
index-check | Condition testing whether loop should continue.  It evaluates to TRUE or FALSE.
index-update | Assignment statement that changes value of index variable.
{ } | Curly braces that enclose the block of statements to be looped.

- The for loop carries out these steps:

Step | Description
1 | Assign the index variable its starting value.  This is specified by <index-start>.
2 | Test if <index-check> is true.  If its true, run the statement block.  If its false, exit the for statement.
3 | Update the index variable per the <index-update>, and return to step 2.

Example 1: loop to display numbers 1 to 10.

Code:

int I;

for (I = 1; I <= 10; I = I + 1)
{
cout << "I is now " << I << endl;
}

Output:

I is now 1
I is now 2
I is now 3
I is now 4
I is now 5
I is now 6
I is now 7
I is now 8
I is now 9
I is now 10

Example 2: loop to prompt for and get a given number of numbers.

Code:

int Count;
int I;
int Num;
cout << "Enter how many numbers you will enter: ";
cin >> Count;
cout << "You will be prompted for " << Count;

if (Count == 1)
{
cout << " number. " << endl;
}
else
{
cout << " numbers. " << endl;
}

for (I = 1; I <= Count; I = I + 1)
{
cout << "Enter the next number: ";
cin >> Num;
cout << "You entered " << Num << endl;
}

Output:

Enter how many numbers you will enter: 4
You will be prompted for 4 numbers.
Enter the next number: 7
You entered 7
Enter the next number: 12
You entered 12
Enter the next number: 6
You entered 6
Enter the next number: 19
You entered 19
All numbers have been entered.