Write a code which inputs two numbers m and n and creates a matrix of size m x n (m rows and n columns) in which every element is either X or 0. The Xs and 0s must be filled alternatively, the matrix should have the outermost rectangle of Xs, then a rectangle of 0s, then a rectangle of Xs, and so on.
Input Format:
The first line of the input consists of an integer, m that correspond to the number of rows in the input array.
The next line of the input consists of an integer, n that corresponds to the number of columns in the input array.
Sample Input:
3
3
Sample Output:
X X X
X 0 X
X X X
Sample Input:
4
5
Sample Output:
X X X X X
X 0 0 0 X
X 0 0 0 X
X X X X X
Program Code:
#include <stdio.h>
void fill0X(int m, int n)
{
int i, k = 0, l = 0;
int r = m, c = n;
char a[m][n];
char x = 'X';
while (k < m && l < n)
{
for (i = l; i < n; ++i)
a[k][i] = x;
k++;
for (i = k; i < m; ++i)
a[i][n-1] = x;
n--;
if (k < m)
{
for (i = n-1; i >= l; --i)
a[m-1][i] = x;
m--;
}
if (l < n)
{
for (i = m-1; i >= k; --i)
a[i][l] = x;
l++;
}
x = (x == '0')? 'X': '0';
}
for (i = 0; i < r; i++)
{
int j;
for (j = 0; j < c; j++)
printf("%c ", a[i][j]);
printf("\n");
}
}
int main()
{
int a,b;
scanf("%d%d",&a,&b);
fill0X(a, b);
return 0;
}
Post A Comment:
0 comments: