Display 3 array values per line

I want to display 3 array values per line
but sadly what I'm trying won't work

1
2
3
4
5
6
7
8
9
for (count3 = ray[0]; count3 >= ray[num1]; count3 )
   {
      cout << count3 << " ";
      if (++n = 3)
      {
         cout << "\n";
         n = 0;
      }
   }
line 6
if(++n == 3)
1
2
3
4
5
6
7
8
9
10
 
for (int i = 0; i < num1; i++)
   {
      cout << ray[i] << " ";
      if (++i == 3)
      {
         cout << "\n";
         i = 0;
      }
   }


outputs
12.2 -200.3
7.6 140.7 67.78 100.1

when its supposed to be

12.2 7.6 -200.3
140.7 890.23 67.78
99.9 100.1
Last edited on
You are incrementing your loop variable twice and resetting the index to zero when it's 3. So you print out elements

ray[0] +1 (no reset) +1 -> 2
ray[2] +1 (reset to 0) +1 -> 1
ray[1] +1 (no reset) +1 -> 3
ray[3] +1 (no reset) +1 -> 5
ray[5] +1 (no reset) +1 -> 7
ray[7] (end)

You can use the reset to zero trick if you use a second variable.

1
2
3
4
5
6
7
8
9
for (int i = 0, j = 0; i < num1; i++)
   {
      cout << ray[i] << " ";
      if (++j == 3)
      {
         cout << "\n";
         j = 0;
      }
   }


But I'd use the modulus operator (%) in this kind of case:

1
2
3
4
5
6
7
8
   for (int i = 0; i < num1; i++)
   {
      cout << ray[i] << " ";
      if ((i + 1) % 3 == 0) // or if(i % 3 == 2)
      {
         cout << "\n";
      }
   }


The +1 is to account for the 0-based indexing. I prefer to use it explicitly so I can always test against 0, as coded, but if you're happy with clock arithmatic you can use the other form, and test against n-1 (where you want n a row).
Last edited on
Topic archived. No new replies allowed.