Using C program: Write a code that prints the perimeter of a 2D array in a count
ID: 3688876 • Letter: U
Question
Using C program:
Write a code that prints the perimeter of a 2D array in a counterclockwise direction. Start printing at the top left comer (row 0, column 0) and move in a counterclockwise direction. Each element on the perimeter should be printed once. Your code should: Use symbolic constants NROWS and NCOLS and use them in writing the code Original array... 12 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 Printing the perimeter counterclockwise... 1, 6, 11, 16/17, 18, 19, 20, 15, 10, 5, 4, 3, 2.Explanation / Answer
/*main.c*/
#include <stdio.h>
#define NROWS 4
#define NCOLS 5
void counterclockwisePrint(int m, int n, int a[NROWS][NCOLS])
{
int i, k = 0, l = 0;
/* k - starting row index
m - ending row index
l - starting column index
n - ending column index
i - iterator
*/
while (k < m && l < n)
{
/* Print the first column */
if (l < n)
{
for (i = k; i <= m-1; ++i)
{
printf("%d ", a[i][l]);
}
l++;
}
/* Print the last row */
if ( k < m)
{
for (i = l; i <= n-1; ++i)
{
printf("%d ", a[m-1][i]);
}
m--;
}
/* Print the last column */
for (i = m; i > k; --i)
{
printf("%d ", a[i-1][n-1]);
}
n--;
/* Print the first row */
for (i = n; i > l; --i)
{
printf("%d ", a[k][i-1]);
}
k++;
}
}
/* Driver program to test above functions */
int main()
{
int a[NROWS][NCOLS] = { {1, 2, 3, 4, 5},
{6, 7, 8, 9, 10},
{11, 12, 13, 14, 15},
{16, 17, 18, 19, 20}
};
counterclockwisePrint(NROWS, NCOLS, a);
return 0;
}
/* OUTPUT:
1 6 11 16 17 18 19 20 15 10 5 4 3 2
*/
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.