for Loops in C++

By: Baski Emailed: 1676 times Printed: 2154 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
4:    #include <iostream.h>
6:    int main()
7:    {
8:      int counter = 0;
10:      while(counter < 5)
11:      {
12:           counter++;
13:           cout << "Looping!  ";
14:      }
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
4:      #include <iostream.h>
6:      int main()
7:      {
8:        int counter;
9:        for (counter = 0; counter < 5; counter++)
10:          cout << "Looping! ";
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 )

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


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++ )
C++ Recursion function explained using Fibonacci series
Sorting an array of Strings in C++
Constructors and Destructors in C++
Dot (.) vs Arrow (->) to access data members in C++
Where to Put Class Declarations and Method Definitions in C++
Using cout.width() in C++
virtual inheritance example in C++
Public versus Private members in C++
while (1) Loops in C++
Calculating total based on the given quantity and price in C++
Demonstration of Prefix and Postfix operators in C++
The Birth, history and need for C++
const Member Functions in C++
Looping with the keyword goto in C++
while Loops in C++
Most Emailed Articles (in C++)
Looping with the keyword goto in C++
Default arguments in C++
Compiling and Linking Multiple Source Files in C++
Difference between Procedural, Structured, and Object-Oriented Programming
Tutorial on Classes and Members in C++
for Loops in C++
Using switch Statements in C++
Operator Precedence in C++
How to handle Exceptions in C++
strcpy() and strncpy() sample program in C++
assert() example program in C++
Using peek() and putback() with cin in C++
Function overloading in C++
File in C++ - Writing text to a file in C++
Pass by Reference vs Pass Value in C++ functions