Help with initializing a 2 dimensional array

I was wondering if there is a better way to factor the following array initialization.

And please no 12 days of Christmas type optimization : )

Thank you.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
  	// initialize the 2 dimensional array
	int row = 0;
	int temp = 0;

	for(int i = 0; i < 3; i++)
	{
		temp = i + 1;
		grid[row][i] = temp;

		 if(i == 2)
		 {
			 row++;
			 for(int col = 0; col < 3; col++)
			 {
				 grid[row][col] = temp += 1;

				 if(col == 2)
				 {
					 row++;
					 for(int colLast = 0; colLast < 3; colLast++)
					 {
						 grid[row][colLast] = temp += 1;
					 }
				 }

			 }

		 }

	}
As I have understood the result array should look as

1 2 3
4 5 6
7 8 9
should not it?

There are many ways to do this. For example to use standard algorithm std::iota. But if you want to use loops yourself then you can do this for example the following way

1
2
3
4
for ( int i = 0; i < 3; i++ )
{
   for ( int j = 0; j < 3; j++ ) grid[i][j] = 3 * i + j + 1;
}


or

1
2
3
4
for ( int i = 0, value = 0; i < 3; i++ )
{
   for ( int j = 0; j < 3; j++ ) grid[i][j] = ++value;
}

Last edited on
Topic archived. No new replies allowed.