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}
};
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, 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';
}
}