Learn C++ - C++ for






The following code shows how to use the for loop.


#include <iostream> 
int main(){ 
     using namespace std; 
     int i;  // create a counter 
     for (i = 0; i < 5; i++) 
         cout << "C++ knows loops.\n"; 
     cout << "C++ knows when to stop.\n"; 
     return 0; 
} 

The code above generates the following result.





Parts of a for Loop

A for loop provides a step-by-step action for performing repeated tasks.

The parts of a for loop handle these steps:

  • Setting a value initially
  • Performing a test to see whether the loop should continue
  • Executing the loop actions
  • Updating value(s) used for the test

The statement following the control section is called the body of the loop, and it is executed as long as the test expression remains true:

for (initialization; test-expression; update-expression) 
   body 

The following code shows how to use numeric test in for loop.


#include <iostream> 
using namespace std; 
int main() //from  w  w w  .j  a va 2s  .  com
{ 
    cout << "Enter the starting countdown value: "; 
    int limit; 
    cin >> limit; 
    int i; 
    for (i = limit; i; i--)     // quits when i is 0 
         cout << "i = " << i << "\n"; 
    cout << "Done now that i = " << i << "\n"; 
    return 0; 
} 

The code above generates the following result.





Note

The program uses one loop to calculate the values of successive factorials.

Then it uses a second loop to display the results.Also the program introduces the use of external declarations for values.


#include <iostream> 
const int SIZE = 16;      // example of external declaration 
int main() 
{ /*from  ww  w .  j  ava2s .c om*/
     long long factorials[SIZE]; 
     factorials[1] = factorials[0] = 1LL; 
     for (int i = 2; i < SIZE; i++) 
          factorials[i] = i * factorials[i-1]; 
     for (int i = 0; i < SIZE; i++) 
          std::cout << i << "! = " << factorials[i] << std::endl; 
     return 0; 
} 

The code above generates the following result.

Changing the Step Size

You can change that by changing the update expression.

The program increases the loop counter by a user-selected step size.


#include <iostream> 
int main() //from w  w w  .ja  v  a 2s. co m
{ 
     using std::cout;   // a using declaration 
     using std::cin; 
     using std::endl; 
     cout << "Enter an integer: "; 
     int by; 
     cin >> by; 
     cout << "Counting by " << by << "s:\n"; 
     for (int i = 0; i < 100; i = i + by) 
       cout << i << endl; 
     return 0; 
} 

The code above generates the following result.

Example

Inside Strings with the for Loop


#include <iostream>
#include <string>
using namespace std;
int main()/* w w w .  ja v a  2 s  . co  m*/
{
    cout << "Enter a word: ";
    string word;
    cin >> word;

    // display letters in reverse order
    for (int i = word.size() - 1; i >= 0; i--)
        cout << word[i];
    cout << "\nBye.\n";
    return 0; 
}

The code above generates the following result.

Compound Statements, or Blocks

The program uses braces to combine three separate statements into a single block.


#include <iostream>
using namespace std;
int main()//from w  ww .  jav a2  s.c  om
{
    cout << "Please enter five values:\n";
    double number;
    double sum = 0.0;
    for (int i = 1; i <= 5; i++)
    {                                   // block starts here
        cout << "Value " << i << ": ";
        cin >> number;
        sum += number;
    }                                   // block ends here
    cout << "They sum to " << sum << endl;
    cout << "and average to " << sum / 5 << ".\n";
    return 0; 
}

The code above generates the following result.

Variable Hidden

If you declare a variable in a block that has the same name as one outside the block, the new variable hides the old one from its point inside the block.

Then the old one becomes visible again, as in this example:


#include <iostream> 
using std::cout; 
using std::endl; 
//w  w w  .j ava 2  s  .c  o m
int main() { 
     int x = 20;   // original x 
     {   // block starts 
         cout << x << endl;  // use original x 
         int x = 100;        // new x 
         cout << x << endl;  // use new x 
     }   // block ends 
    cout << x << endl;      // use original x 
    return 0; 
} 

The code above generates the following result.

Example 2

The following code shows how to reverse an array.


#include <iostream> 
#include <string> 
using namespace std; 
int main() { /*w  ww  .  java  2  s . c  o  m*/
     
     cout << "Enter a word: "; 
     string word; 
     cin >> word; 

     char temp; 
     int i, j; 
     for (j = 0, i = word.size() - 1; j < i; --i, ++j) 
     {                       // start block 
         temp = word[i]; 
         word[i] = word[j]; 
         word[j] = temp; 
     }                       // end block 
     cout << word << "\nDone\n"; 
     return 0; 
} 

The code above generates the following result.

Example 3

The follownig code shows how to skip non-numeric input.


#include <iostream>
using namespace std;
const int Max = 5;
int main()//  w w w  . j ava  2s  .  co m
{
    int golf[Max];
    cout << "You must enter " << Max << " rounds.\n";
    int i;
    for (i = 0; i < Max; i++)
    {
        cout << "round #" << i+1 << ": ";
        while (!(cin >> golf[i])) {
            cin.clear();     // reset input
            while (cin.get() != '\n')
                continue;    // get rid of bad input
            cout << "Please enter a number: ";
        }
    }

    double total = 0.0;
    for (i = 0; i < Max; i++)
        total += golf[i];
    cout << total / Max << " = average score " << Max << " rounds\n";

    return 0; 
}

The code above generates the following result.