The problem is to fill the array like this if n = 4
output of my code:
1 2 3 4
1 2 3 4
1 2 3 4
1 2 3 4
desired output:
1 2 3 4
2 3 4 3
3 4 3 2
4 3 2 1
My friend said this problem is easy but I can’t figure it out, please help. The code I wrote:
#include <stdio.h>
main()
{
int i,j,n;
int a[100][100];
printf("Enter the value of n:");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
a[i][j]=j;
}
}
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
printf("%d ",a[i][j]);
}
printf("\n");
}
}
>Solution :
You always start counting from 1 upwards, but you don’t have a loop where you count backwards, like in the desired output.
I would recommend to use two for loops, one which counts upwards and one downwards. Also you don’t need an array, you can print out the numbers directly:
main()
{
int i,j,n;
printf("Enter the value of n:");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
for(j = i; j < n; j++)
{
printf("%d ", j);
}
for(j = n; j > n-i; j--)
{
printf("%d ", j);
}
printf("\n");
}
}