Code About Us Tutorial


  Statements & Expression
    The while Statement
    The do ... while Statement
    The for Statement
    The break Statement
    The continue Statement
    The goto Statement
    The switch Statement
    Keywords
    Scope Resolution (::)
    Arithmatic Operators


   
 

Home > Statements & Expression > The for Statement

November 30, 2009 11:02 am

   

The for Statement

Finally let us cover the for Statement. Three separate parts control a loop:
  1. an initialization,
  2. a continuation condition, and
  3. an update.

You'll see what I'm talking about when you see the code. The syntax for the for statement is

for (initialization; continuation condition; update) statement;

The initialization, the continuation condition, or the update may be empty. Here is an example:
 
 
#include <iostream.h>

int main() { int n1, sum; cout << "Enter a number to be counted: "; cin >> n1;

for(int i = 0; i < n1; i++) { sum = i+1; cout << sum << "n"; } return 0; }

This program will ask the user to enter a number, and then once it receives the number it will count up to that number and stop. Here the initialization is int i = 0, the continuation condition is i < n1, and the update is i++. In the for loop, the sum is the counter i + 1, each time it goes threw the loop it will add one to the sum. The first time around the sum is changed to 1, the 2nd time it is 2 and so on. Please Rate this Code:


    Comments for: The for Statement
Annonymouse User says:

Annonymouse User says:
says:
cout << sum << \"n\"; cout << sum << \" \";

Why not use white space in inverted brackets to get 1 2 3 4 5 etc instead 1n2n3n4n5n etc.





Add Comment:
Name:
Email:


 «26» THINKQUEST TEAM C0111571 © 2001. All Rights Reserved.