I'm trying to print diagonals in an array but I have no idea why my code isn't working. The upper and lower functions work but I have a hard time tinkering with the column elements. For example, in the upper function I have no idea why my code works without resetting the y value to 0 after every row. In fact, it doesn't work if I did reset.
Code:
#include <stdio.h>
int matrix[5][5];
int upper ()
{
int a, b, x = 0, y = 0;
for (a = 0; a < 5; a++, x++, b++)
{
for (b = 0; b < 4; b++, y++)
{
matrix[x][y] = 1;
}
}
return matrix[5][5];
}
int diagonal ()
{
int x, y;
for (x = 0, y = 5; y > 0; x++, y--)
{
matrix[x][y] = 3;
}
return matrix[5][5];
}
int lower ()
{
int a, b, c, x = 0, y = 5;
for (a = 0; a < 5; a++, x++)
{
for (b = 0, c = 1; b < c && c < 5; c++, y++)
{
matrix[x][y] = -1;
}
}
return matrix[5][5];
}
int main (void)
{
int a = 0, b = 0, i, j, k;
upper ();
lower ();
diagonal();
for (i = 0; i < 5; i++, a++)
{
for (j = 0; j < 5; j++, b++)
{
printf("%d\t", matrix[a][b]);
}
printf("\n");
}
return 0;
}