C++

Can you declare Multiple Variables in a for-Loop in C++?

Declaration of a variable, means identifying a memory location for the variable content. Well, the answer is, Yes. Start by considering the following code segment:

int i = 0;
int j = 0;
int k = 0;

These are three statements that can be written in one statement, as:

int i = 0, j = 0, k = 0;

There is one data type; the expressions are separated by commas. A statement ends with one semicolon. Multiple variables have been declared here in one statement.

Now, consider the following incremental statements:

int i++;
int j++;
int k++;

These three statements can be replaced by one statement, as follows:

int i++, j++, k++;

Here, there are three expressions in one statement for one data type.

Also consider the following three conditional statements:

i < 10;
j < 10;
k < 10;

These three statements, can be replaced by one statement, as follows:

i < 10 && j < 10 && k < 10;

Here, three statements have been combined into one expression of a special form. These expressions are not separated by commas as in the above cases, but they are combined with the logical AND.

This article explains how multiple variables can be declared and used, in a for-loop, with regular correspondences. Very simple examples are used for illustrations.

Article Content

One Dimensional for-loop

while-Loop

A while-loop to display numbers from zero to 9, is as in the following program:

#include <iostream>
using namespace std;

int main() {

        int i=0;

        while (i < 10) {
            cout << i << endl;
            i++;
        }
     
        return 0;
    }

The first line in the program includes the iostream library for the cout object. The next line in the program is a statement. It ensures that any name used is from the C++ standard library unless otherwise indicated.

In the main() function, there is the initialization statement, of the integer, i = 0. Then there is the while-loop, which takes into account the initialization statement. The while-condition is (i < 10), and as long as i is less than 10 (never equal to 10), the cout iostream object in the body of the while-loop displays the value of i. The next statement in the while-loop increments i (adds 1 to the value of i).

The output is as follows but displayed vertically:

0 1 2 3 4 5 6 7 8 9

One Dimensional for-Loop

The code in the main() function above, is reproduced, in the following program, as a for-loop:

#include <iostream>
using namespace std;

int main(){

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

The output is the same as in the above case. The initialization statement for the above code is now the first statement in the parentheses of the for-loop, followed by a semicolon. The while-condition for the above code is now the second statement in the parentheses of the for-loop, followed by a semicolon. The increment statement in the body of the while-loop, for the previous code, is now the third statement in the parentheses of the for-loop. It is not followed by a semicolon because it is the last statement in the parentheses. The only statement in the for-loop displays the value of i.

Two Dimensional for-loop
Nested while-loop

The above one-dimensional for-loop displays one column, where each cell has a number, the value of i. A while-loop, nested in another while-loop, would display a table, where each cell would have a number (the value of j at that position). The following program illustrates this:

#include <iostream>
using namespace std;

int main() {

        int i=0;
        while (i < 5) {
            int j=0;
            while (j < 5) {
                cout << j << ' ';
                j++;
            }
            cout << endl;
            i++;
        }
     
        return 0;
    }

The output is:

0 1 2 3 4
0 1 2 3 4
0 1 2 3 4
0 1 2 3 4
0 1 2 3 4

The i variable determines the rows. The j variable determines the columns. The maximum values for i and j are each 4 in this code. No value of i is printed. For each value of j, the value of j is printed horizontally. j is incremented to print the next value horizontally for each line.

There are two initialization statements: one for i and one for j, both initialized to zero. The initialization statement for j is within the outer loop. In this way, j is reinitialized for each row (each horizontal line). In this way, j can produce numbers from 0 to 4 for each row. The value of i is never printed; it only indicates the row number. i is incremented outside and below the nested loop. i is incremented for the purpose of the next row.

Nested for-loop

The following nested for-loop produces the same result (table) as the above nested while-loop:

#include <iostream>
using namespace std;

int main(){

        for (int i=0; i < 5; i++) {
            for (int j=0; j < 5; j++) {
                cout << j << ' ';
            }
            cout << endl;
        }
     
        return 0;
    }

Each for-loop's parentheses have its own initialization statement, its own condition statement, and its own increment statement.

One while-loop

The above table output can be produced by one while-loop, with one initialization statement and one condition statement. However, re-assignment of zero to j and increment of i has to occur in an if-construct. The following code illustrates this:

#include <iostream>
using namespace std;

int main(){

        int i=0, j=0;
        while (i < 5 && j <5) {
            cout << j << ' ';
            j++;
            if (j == 5) {
                cout << endl;
                j=0;
                i++;
            }
        }
     
        return 0;
    }

The output is the same table as the one above.

One for-loop

The above table output can be produced by one for-loop, with one initialization statement and one condition statement. However, re-assignment of zero to j and increment of i has to occur in an if-construct. The following program illustrates this:

#include <iostream>
using namespace std;

int main() {
        for (int i=0, j=0; i < 5 && j <5; j++) {
            cout << j << ' ';
            if (j == 4) {
                cout << endl;
                j = -1;
                i++;
            }
        }
     
        return 0;
    }

The output is the same table as the one above. However, here, since j is incremented at the end of the loop, in the parentheses, the if-condition is (j == 4), and j is re-assigned, -1 for each row.

What is spacial here is that two variables have been declared in a for-loop. And so, multiple variables can be declared in a for-loop.

Leading Diagonal Addressing

In a square table, the leading diagonal is the diagonal from the top-left end to the bottom-right end. The following program displays the coordinates of the leading diagonal of the above table:

#include <iostream>
using namespace std;

int main() {

        for (int i=0, j=0; i < 5 && j <5; i++,j++) {
            cout << i << ',' << j << ' ';
        }
        cout << endl;
     
        return 0;
    }

The output is:

0,0 1,1 2,2 3,3 4,4

Notice that in the program, two variables have been declared in the parentheses of the for-loop; the condition has the two variables, related by the logical AND; and the increment statement has the two variables, each incremented by adding one. Under this condition, the one statement in the body of the for-loop prints the coordinates of the leading diagonal.

Three Dimensional for-loop

It can be cumbersome to print all the values of the cells of a cube. The following program just prints the coordinates of the leading diagonal of a cube:

#include <iostream>
using namespace std;

int main(){

        for (int i=0,j=0,k=0; i<5&&j<5&&k<5; i++,j++,k++) {
            cout << i << ',' << j << ',' << k << ' ';
        }
        cout << endl;
     
        return 0;
    }

The output is:

0,0,0 1,1,1 2,2,2 3,3,3 4,4,4

Notice that the initialization statement has three variables; the condition statement has the three variables, and the increment statement has the three variables. There is only one statement in the body of the for-loop.

Possible Advantage

Consider a single for-loop to display all the values of the cells of a square table:
Having the two variables in the initialization statement and in the condition does not bring any advantage in speed, compared to the situation where one loop is nested.

However, if only selected values in the table are to be accessed, then having the two variables, in the initialization statement, in the condition statement, and in the increment statement, would bring an advantage in speed; in the sense that all the values will not be accessed, before eliminating many of them. In the following program, every other coordinate pair, in the leading diagonal, is printed:

#include <iostream>
using namespace std;

int main()    {

        for (int i=0, j=0; i < 10 && j <10; i+=2,j+=2) {
            cout << i << ',' << j << ' ';
        }
        cout << endl;
     
        return 0;
    }

The output is:

0,0 2,2 4,4 6,6 8,8

There is still only one statement in the for-loop. Gaining advantage in speed, in this way, involves including additional selective logic in the condition statement and/or in the increment statement. The initialization expressions in the initialization statement may not have to be initialized to zero.

In the above code, the increment statement is:

i+=2,j+=2

which means,

i = i+2, j = j+2;

Conclusion

Yes, I can declare multiple variables in a for-loop. And you, too, can now declare multiple variables, in a for-loop, as follows: Just separate the multiple variables in the initialization statement with commas. Do not forget to end the complete initialization statement with a semicolon. If the access of the elements of the structure has to be selective, then these variables may have to be used as well, in the condition and/or increment statements, in the parentheses of the for-loop, possibly with some additional logic.

About the author

Chrysanthus Forcha

Discoverer of mathematics Integration from First Principles and related series. Master’s Degree in Technical Education, specializing in Electronics and Computer Software. BSc Electronics. I also have knowledge and experience at the Master’s level in Computing and Telecommunications. Out of 20,000 writers, I was the 37th best writer at devarticles.com. I have been working in these fields for more than 10 years.