Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

C program to fill an array

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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");
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading