The case scenario:
A 2-D array is given:
1 3 6 10 15
2 5 9 14 19
4 8 13 18 22
7 12 17 21 24
11 16 20 23 25
and its size N is given as 5.
The program should output it as
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
The code I wrote for this problem:
#include <stdio.h>
void main()
{
int N = 5;
int pixel_array[5][5] = {
{1, 3, 6, 10, 15}, {2, 5, 9, 14, 19}, {4, 8, 13, 18, 22}, {7, 12, 17, 21, 24}, {11, 16, 20, 23, 25}
};
for (int row = 0; row < N; row++)
{
if (row < N - 1)
{
for (int temp_row = row, col = 0; temp_row >= 0; temp_row--, col++)
printf("%d ", pixel_array[temp_row][col]);
}
else
{
for (int col = 0; col < N; col++)
for (int temp_col = col, temp_row = N - 1; temp_col < N; temp_col++, temp_row--)
printf("%d ", pixel_array[temp_row][temp_col]);
}
}
}
The above code works fine and outputs the required result.
Some specific questions:
Since there are many for loops here -
- how can I decrease code length?
- how can I improve the efficiency of this program?
- Any other programming practices to be implemented?
Any advice would help.