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).