tags:

views:

305

answers:

7

Possible Duplicate:
How to put 2 increment statements in c++ for loop?

How do I declare 2 counters in a for loop in c++

+11  A: 

Yay for comma operator:

for (int i =0, j = 0; i < 6 && j < 5; ++i,++j)
{
   ...
}

This operator separates multiple expressions in one statement for situations just like this.

Doug T.
But just to be clear, the comma in `int i = 0, j = 0;` is not the comma operator.
GMan
+3  A: 

Use the comma operator:

for (int i = 0, j = 0; i < 5 && j < 5; ++i, ++j) {}
Thomas Jones-Low
My compiler gives: `unexpected unqualified-id before 'int'` - you need to remove that second int.
Michael Anderson
+2  A: 

Commas!

for (i = 0, j = 10; i <= j; i++, j--) {
   printf("%d + %d = 10\n", i, j);
}

Which shows:

0 + 10 = 10
1 + 9 = 10
2 + 8 = 10
3 + 7 = 10
4 + 6 = 10
5 + 5 = 10
yjerem
+2  A: 

For example...:

$ cat a.cc
#include <iostream>

int main()
{
  for(int i=7, j=3; (j<30) && (i<40); i+=3, j+=2) {
    std::cout << "i: " << i << ", j: " << j << std::endl;
  }
  return 0;
}

$ g++ -Wall -pedantic a.cc
$ ./a.out 
i: 7, j: 3
i: 10, j: 5
i: 13, j: 7
i: 16, j: 9
i: 19, j: 11
i: 22, j: 13
i: 25, j: 15
i: 28, j: 17
i: 31, j: 19
i: 34, j: 21
i: 37, j: 23
$ 
Alex Martelli
A: 

Just wanted to add that you don't necessarily need to include a reference to the second 'counter' in the condition (middle) argument to the loop. For example, the following is valid C:

for ( int i = 0, j = 10; i < 5; i++, j-=2 ) { ... }

johnny_bgoode
A: 

what's your means 2 counters in a for loop in c++? more solution for different requirement, what does you want?

bygreencn