pay, digits, number

C++ For Loop

The For Loop Definition

The FOR loop in C and C++ is very powerful and in some ways, outclasses the FOR loop in other languages.  Its basic definition looks like this:

				
					for(Initializer;  Test;  Incrementor)
{
    foo();
    foowho();
};
				
			
Or
				
					
for(Initializer; Test; Incrementor)
    foo();   // Loopy stuff done here
				
			

Lets look at an example of counting from 0 to 9:

				
					int x;
for (x = 0; x < 10; x++)
{
    cout << x << ' ';
};

// 0 1 2 3 4 5 6 7 8 9
				
			

x=0;  This Initializer sets our counter to 0. Initializers only execute once at the beginning of the loop.

x < 10; Next is the Testor. The Testor is executed before every loop and must result in TRUE or FALSE.  In this example, we check that x is less than 10, and if it is, go ahead and do the next iteration of the loop.

x++;  The Incrementor is typically used to increase the counter variable and will be executed at the end of every loop.  In our case, we’re incrementing x by one.  After this is done, C++ returns to the Testor to ensure x is still in range, and if so, continues to loop.  Otherwise, the loop ends.

For Loop Bodies

It’s worth noting that the For loop can have an optional body between curly brackets, or a single statement attached to it.  Having a body allows you to attach multiple statements to a single For loop.  These two For loops are functionally equivalent:

				
					int x;
for (x = 0; x < 10; x++)
{
    cout << x << endl;
}

for (x = 0; x < 10; x++)
    cout << x << endl;
				
			

The next two For loops are NOT equivalent.

				
					int x;
for (x = 0; x < 10; x++)
{
    cout << x << ' ';
    if (x == 5)
        cout << " X = 5!! ";
}

cout << endl;

for (x = 0; x < 10; x++)
    cout << x << ' ';
    if (x == 5)
        cout << " X = 5!! ";
        
------------------------------------- 
0 1 2 3 4 5 X = 5!! 6 7 8 9
0 1 2 3 4 5 6 7 8 9

				
			

Notice how the 2nd row of numbers, produced by the 2nd For statement in the above example doesn’t display “X = 5!!”.  This is because the For statement is only operating on a single statement underneath it:

cout << x << ' ';

The For loop needs curly braces to define a body if more than one statement is to be executed.

Accessing Arrays

Using a for loop to access an array is pretty typical.  Here is an example:

				
					int Primes[] = { 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97 };
int x;
for (x = 0; x < 25; x++ )
{
  cout << Primes[x] << ' ';
};
>> 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97</pre>

Break; Exit The Loop

There are times when it’s useful to break out of a For loop before you are done.  For example, you’re searching an array for a particular value.  Once it’s found, you don’t need to check the rest of the array.

				
					int Primes[] = { 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97 };

int x;
int LookFor = 31;

for (x = 0; x < 25; x++ )
{
    cout << Primes[x] << ' ';
    if (Primes[x] == LookFor)
        break;
};
>> 2 3 5 7 11 13 17 19 23 29 31
				
			

Continue; Top of the Loop Please

Encountering the continue keyword causes the loop to immediately start a new iteration, ignoring any code that comes after it.

				
					for (int x = 0; x < 10; x++)
{
    if (x < 5)
        continue;
    cout << x << ' ';
};

>> 5 6 7 8 9
				
			

Nested For Loops

For loops can be nested.  Consider this example:

				
					int x, y;
for (x = 0; x < 5; x++)
    for (y = 2; y < 4; y++) 
        cout << "X=" << x << " Y=" << y << endl;
--------------------------------------------------
X=0 Y=2
X=0 Y=3
X=1 Y=2
X=1 Y=3
X=2 Y=2
X=2 Y=3
X=3 Y=2
X=3 Y=3
X=4 Y=2
X=4 Y=3
				
			

We can see the inner loop (y) executes completely for each time the outer loop (x) completes a single iteration.

Multiple Initializers and Incrementors

Consider this example:

				
					int x, y;
for (x = 0, y = 10; y < 25; x++, y+=2)
{
    if (x < 5)
        continue;
    cout << x << ' ' << y <<' ';
}

>> 5 20 6 22 7 24
				
			

As long as you’re not defining a variable in the Initializer, you can add multiple Initializers, separated by a comma.  And you can assign multiple Incrementors, separated by commas as well.

				
					int x, y;
for (x = 0, y = 10; y < 25; x++, y+=2, cout << y << endl)
{
    cout << x << ' ' << y << ' ';
}

--------------------------------------------------- 
0 10 12
1 12 14
2 14 16
3 16 18
4 18 20
5 20 22
6 22 24
7 24 26
				
			

First, the example prints the value of x and y.  The first loop iteration. Next, the loop executes the Incrementors.  In this case, we told it to increase x and y, but also to print y’s value.  Nearly any statement can be present here, even a call to a function.  For example:

				
					void hi(int value)
{
    cout << value << endl;
}

int main()
{
    int x, y;
    for (x = 0, y = 10; y < 25; x++, y+=2, hi(y)) cout << x << ' ' << y << ' ';
}
---------------------------------------------------
0 10 12
1 12 14
2 14 16
3 16 18
4 18 20
5 20 22
6 22 24
7 24 26
				
			

The third column is produced by the Hi() function.

Tips and Tricks

				
					for(;;);
				
			

This is known as the infinite loop.  Its the very same as writing:

				
					while(1);
				
			

This brings me to my next point – all of the operators within the For loop are optional.  Consider this code:

				
					int x;
for (x = 0; ; x++)
    cout << x << ' ';
				
			

Notice the Testor function is missing. Normally between those two semicolons, we would see something like x<10, but in this case, it’s blank.  In a situation like this, a missing Testor always evaluates to true.  This piece of code results in an infinite loop, printing all the values of x along the way.

You can also choose to exclude an Incrementor, like this

				
					int x;
for (x=0; x < 10 ;)
    cout << x++ << ' ';
				
			

x is still incremented, but not until the cout command. And of course, you don’t need an Initializer:

				
					int x = 0;

for ( ; x < 10 ; )
    cout << x++ << ' ';
				
			

And of course you can declare and initialize a variable within the For loop:

				
					
for ( int x = 0 ; x < 10 ; )
	cout << x++ << ' ';
				
			

In this case, x is encapsulated within the for loop and will not be available to the rest of your program after the for loop ends.  It is removed from memory just as all local variables are removed from memory as they go out of scope.

Conclusion

The For loop is a powerful, multi-faceted, and often used feature of C and C++.  Its power is limited only by your imagination since its extendable, flexible, and hackable.  Much of the plumbing can be handled by the For loop, creating a cleaner, leaner workspace.  You will find the For loop to be an indispensable part of your programs. 

Leave a Comment