for Loops in C++

By: Baski Emailed: 1728 times Printed: 2331 times    

Latest comments
By: rohit kumar - how this program is work
By: Kirti - Hi..thx for the hadoop in
By: Spijker - I have altered the code a
By: ali mohammed - why we use the java in ne
By: ali mohammed - why we use the java in ne
By: mizhelle - when I exported the data
By: raul - no output as well, i'm ge
By: Rajesh - thanx very much...
By: Suindu De - Suppose we are executing

When programming while loops, you'll often find yourself setting up a starting condition, testing to see if the condition is true, and incrementing or otherwise changing a variable each time through the loop. The following program demonstrates this.

While reexamined.

1:    // 
2:    // Looping with while
3:
4:    #include <iostream.h>
5:
6:    int main()
7:    {
8:      int counter = 0;
9:
10:      while(counter < 5)
11:      {
12:           counter++;
13:           cout << "Looping!  ";
14:      }
15:
16:      cout << "\nCounter: " << counter << ".\n";
17:       return 0;
18: }
Output: Looping!  Looping!  Looping!  Looping!  Looping!
Counter: 5.

Analysis: The condition is set on line 8: counter is initialized to 0. On line 10, counter is tested to see whether it is less than 5. counter is incremented on line 12. On line 16, a simple message is printed, but you can imagine that more important work could be done for each increment of the counter.
A for loop combines three steps into one statement. The three steps are initialization, test, and increment. A for statement consists of the keyword for followed by a pair of parentheses. Within the parentheses are three statements separated by semicolons.

The first statement is the initialization. Any legal C++ statement can be put here, but typically this is used to create and initialize a counting variable. Statement 2 is the test, and any legal C++ expression can be used here. This serves the same role as the condition in the while loop. Statement 3 is the action. Typically a value is incremented or decremented, though any legal C++ statement can be put here. Note that statements 1 and 3 can be any legal C++ statement, but statement 2 must be an expression--a C++ statement that returns a value. The program below demonstrates a for loop.

Demonstrating the for loop.

1:      //
2:      // Looping with for
3:
4:      #include <iostream.h>
5:
6:      int main()
7:      {
8:        int counter;
9:        for (counter = 0; counter < 5; counter++)
10:          cout << "Looping! ";
11:
12:        cout << "\nCounter: " << counter << ".\n";
13:         return 0;
14: }
Output: Looping!  Looping!  Looping!  Looping!  Looping!
Counter: 5.

Analysis: The for statement on line 8 combines the initialization of counter, the test that counter is less than 5, and the increment of counter all into one line. The body of the for statement is on line 9. Of course, a block could be used here as well.

The for Statement

The syntax for the for statement is as follows:

for (initialization; test; action )
statement;

The initialization statement is used to initialize the state of a counter, or to otherwise prepare for the loop. test is any C++ expression and is evaluated each time through the loop. If test is TRUE, the action in the header is executed (typically the counter is incremented) and then the body of the for loop is executed. Example 1

// print Hello ten times
for (int i = 0; i<10; i++)
cout << "Hello! ";

Example 2

for (int i = 0; i < 10; i++)
{
    cout << "Hello!" << endl;
    cout << "the value of i is: " << i << endl;
}

C++ Home | All C++ Tutorials | Latest C++ Tutorials

Sponsored Links

If this tutorial doesn't answer your question, or you have a specific question, just ask an expert here. Post your question to get a direct answer.



Bookmark and Share

Comments(0)


Be the first one to add a comment

Your name (required):


Your email(required, will not be shown to the public):


Your sites URL (optional):


Your comments:



More Tutorials by Baski
Compiling multiple source files and specifying classpath using javac
The equals() Method example in Java
Default Values for Data Types in Java
JSP Example to connect to MS SQL database using Tomcat Connection Pool
<convertNumber> and <convertDateTime> in JSF
Enable/Disable Scripting Elements in JSP
Using calloc() Function in C
lseek() sample program in C
Arrays of Structures example program in C
The Basic Syntax Expression Language in JSP
Initialization of Pointer Arrays in C
Functions returning non-integer values in C
Increment and Decrement Operators in C
Getting Started with C
What is JSF (JavaServer Faces)?

More Tutorials in C++
Two-Dimensional Array Manipulation in C++
Calculate average using Two-Dimensional Array in C++
Compute the square root of the sum of the squares of an array in C++
Matrix using nested for loops in C++
Sorting an array of Strings in C++
Calculating total based on the given quantity and price in C++
Compiling and Linking Multiple Source Files in C++
Enumerations in C++
Program to add two numbers in C++
Comments in C++
while loop in C++
for loop in C++
Programming errors a compiler will detect in C++
if in C++
Using the Built-in Arithmetic Types in C++

More Latest News
Most Viewed Articles (in C++ )
Dot (.) vs Arrow (->) to access data members in C++
Calculating total based on the given quantity and price in C++
Difference between Procedural, Structured, and Object-Oriented Programming
The indirection operator (*) - dereference operator.
strcat() and strncat() sample program in C++
Using peek() and putback() with cin in C++
Using cout.width() in C++
Using cout.fill() in C++
Sum of 1 to N in C++
Calculate average using Two-Dimensional Array in C++
Using cout in C++
Using Comments in a C++ Program
Use of Conditional (Ternary) Operator in C++
C++ Recursion function explained using Fibonacci series
Public versus Private members in C++
Most Emailed Articles (in C++)
Matrix using nested for loops in C++
The if Statement in C++
Returning values from a function in C++
What Is a Pointer in C++?
C++ Destructors Versus Java Finalization
Operator Precedence in C++
How to handle Exceptions in C++
atoi(), itoa() in C++
Using cout.fill() in C++
Multiple inheritance example in C++
for loop in C++
Using the Built-in Arithmetic Types in C++
Two-Dimensional Array Manipulation in C++
Calculate average using Two-Dimensional Array in C++
Sorting an array of Strings in C++