Print magic array

I've created a program which works as it should, it has an array and it prints out the array in a 3x3 square. However when revisiting the program I've got confused at how it works regarding the loop and I stupidly didn't include comments to re-jog my memory. Can someone explain why I've put the loop in/how it works with the loop - why does it need the loop to print the array in that format?

Thanks.


using namespace std;


int main()
{
int magic[3][3] = {
{2, 7, 6},
{9, 5, 1},
{4, 3, 8}
};



for (int i = 0; i < 3; i++)
{

for (int j = 0; j < 3; j++)
{


cout << magic[i][j]<<" ";


}cout << endl;
}

}
Last edited on
This piece of code prints the number at row i, column j.
 
cout << magic[i][j] << " ";

This piece of code prints row i.
1
2
3
4
5
for (int j = 0; j < 3; j++)
{
	// print number at row i, column j ...
}
cout << endl;

This piece of code prints all the rows.
1
2
3
4
for (int i = 0; i < 3; i++)
{
	// print row i ...
}
Last edited on
But why do you have to put:

for (int i = 0; i < 3; i++)
{

for (int j = 0; j < 3; j++)


You need two loops because it's a two-dimensional array. If you had a three-dimensional array (int magic[3][3][3]) you would have to use three loops.
Last edited on
So does it work like this:

at the first its i=0; i is less than 3 as it is currently 0,
then it goes to the nested loop:

j=0, j is less than 3 because its currently 0, so it prints 2,
j can be incremented to 1, 1 is less than 3 so it can print 9,
j can be incremented again, 2 is less than 3 so it can print 4.

i is now 1, 1 is less than 3,
goes to nested loop:

j = 0, j is less than 3 so it prints 7,
j can be incremented to 1 which is still less than 3 so it prints 5
etc.
Yes, except that it prints row by row.
2, 7, 6, then 9, 5, 1, ...
Ah ok I get it. Thanks for your help
Yes, but you forgot one thing: what does happen after j has become 3 and before i increments?


"have to" ...
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// my first program in C++
#include <iostream>

int main()
{
  constexpr size_t D {3};
  int magic[D][D] {
    2, 7, 6,
    9, 5, 1,
    4, 3, 8 };

  for ( size_t e = 0; e < D*D; ++e )
  {
    std::cout << magic[e/D][e%D] << ' ';
    if ( 0 == (e + 1) % D ) std::cout << '\n';
  }
}
Topic archived. No new replies allowed.