Search code examples
cnested-loops

Why this code is working for 1 and 2 yet fails for input that is more than 3?


So I am trying to print patterns in C.

For n = 2
Output:
2 2 2
2 1 2
2 2 2
for n = 3
Output:
3 3 3 3 3
3 2 2 2 3
3 2 1 2 3
3 2 2 2 3
3 3 3 3 3 
and so on.

My Code:

#include <stdio.h>
#include <stdlib.h>
    
int main()
{
    int n;
    scanf("%d",&n);
    int nn = n;
    int *arr;
    arr = (int*)malloc(n*sizeof(int));
    int f = 0; //flag to check if I reached the mid of the pattern
    int l = 2*n-1; //Lenght of square to be generated
    int temp1 = 0;
    int temp2 = l;
    for(int i = 0;i<l;i++)
    {
        for(int j = temp1;j<temp2;j++) //change values in range temp1 to temp2
        {
            arr[j] = n;
        }
        for(int k = 0;k<l;k++)
        {
            printf("%d ",arr[k]);
        }
        printf("\n");
        if(n == 1)
        {
            f = 1;
        }
        if(f==0)        //For upper half of pattern
        {
            n=n-1;
            temp1=temp1+1;
            temp2=temp2-1;
        }
        else if(f==1) //For lower half of pattern
        {
            n=n+1;
            temp1=temp1-1;
            temp2=temp2+1;
        }
    }
    return(0);
}

I am getting the correct output for n = 2 but when I am inputting anything above 2 the code is crashing. I am not able to find what should be done. Can someone help me out and tell me what am I doing wrong?


Solution

  • It would be better to check distances by axis and take a maximum of them to be printed.

    Something like:

    #include <stdio.h>
    #include <stdlib.h>
    
    int main()
    {
        int vertical_distance;
        int horizontal_distance;
        
        int n;
        scanf("%d",&n);
        for(int i = 0; i < n * 2 + 1; i++)
        {
            for(int j = 0; j < n * 2 + 1; j++)
            {
                vertical_distance   = abs(n - i);
                horizontal_distance = abs(n - j);
                if (vertical_distance > horizontal_distance)
                    printf("%d ", vertical_distance);
                else
                    printf("%d ", horizontal_distance);
            }
            printf("\n");
        }
        return(0);
    }
    

    Also, when I ran your code it worked nicely with large numbers (3, 7, 15). I just pasted your code to onlinegdb.com/online_c_compiler and ran it. Can you please add the error message that you have got?

    (sry for my English)