Print repeating diagonal in array

Hi,

I'm trying to print a repeating pattern of numbers, going from 1 to 5, in the diagonal of a 20 x 20 array, but my code isn't producing anything. What am I doing wrong?

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
31
32
33
34
#include <iostream>
int main()
{
	int a[20][20];
	int c[5] = { 1,2,3,4,5 };

	for (int i = 0; i < 20; i++)
	{
		for (int j = 0; i < 20; j++)
		{
			if (i != j)
				a[i][j] = 0;
		}
	}

	for (int i = 0; i < 20; i += 5)
	{
		a[i][i] = c[0];
		a[i + 1][i + 1] = c[1];
		a[i + 2][i + 2] = c[2];
		a[i + 3][i + 3] = c[3];
		a[i + 4][i + 4] = c[4];
	}

	for (int i = 0; i < 20; i++)
	{
		for (int j = 0; j < 20; j++)
		{
			std::cout << a[i][j];
		}
		std::cout << '\n';
	}

}


it should be

1 0 0 0 0 0 0 0 0 0 0 .....
0 2 0 0 0 0 0 0 0 0 0 .....
0 0 3 0 0 0 0 0 0 0 0 .....
0 0 0 4 0 0 0 0 0 0 0 .....
0 0 0 0 5 0 0 0 0 0 0 .....
0 0 0 0 0 1 0 0 0 0 0 .....
0 0 0 0 0 0 2 0 0 0 0 .....
0 0 0 0 0 0 0 3 0 0 0 .....
0 0 0 0 0 0 0 0 4 0 0 .....
0 0 0 0 0 0 0 0 0 5 0 .....
0 0 0 0 0 0 0 0 0 0 1 .....

Thank you for your help!

Edit:

NVM, I got it to work using the code below. Is there a better way of doing this though? 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
31
32
33
34
#include <iostream>
int main()
{
	int a[15][15];
	int c[5] = { 1,2,3,4,5 };

	for (int i = 0; i < 15; i++)
	{
		for (int j = 0; j < 15; j++)
		{
			if (i != j);
			a[i][j] = 0;
		}
	}

	for (int i = 0; i < 15; i += 5)
	{
		a[i][i] = c[0];
		a[i + 1][i + 1] = c[1];
		a[i + 2][i + 2] = c[2];
		a[i + 3][i + 3] = c[3];
		a[i + 4][i + 4] = c[4];
	}

	for (int i = 0; i < 15; i++)
	{
		for (int j = 0; j < 15; j++)
		{
			std::cout << a[i][j];
		}
		std::cout << '\n';
	}

}

Last edited on
Use “modular arithmetic”.

The idea is that you have a remainder. For example, the following list of numbers:

    0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
 
can be converted into a repeating range by dividing them by some number (like 5) and keeping the remainder:

    0 1 2 3 4 0 1 2 3 4 0 1 2 3 4 0 1 2

In C and C++, the “remainder” operator is %, as in:

    remainder = number % divisor;
 

The next trick is to see how the index into the array’s diagonal relates to the values you want.

Hope this helps.
Last edited on
Topic archived. No new replies allowed.