Printing Pattern Using Loops

Sort by

recency

|

1051 Discussions

|

  • + 0 comments

    I have a solution which is way faster and more simple than using the array

    include

    include

    include

    include

    int main() {

    int n;
    scanf("%d", &n);
    // Complete the code to print the pattern.
    for (int i = 1; i <= 2 * n - 1; i++) {
        int d = abs(i - n);
        for(int j = 1; j <= n - 1 - d; j++) printf("%d ", n - j + 1);
        for(int j = 1; j <= 2 * d + 1; j++) printf("%d ", d + 1);
        for(int j = n - 1 - d; j >= 1; j--) printf("%d ", n - j + 1);
        printf("\n");
    
    }
    return 0;
    

    }

  • + 0 comments

    how do you see this solution

    int max(int a, int b){
        if(a < b) return b;
        return a;
    }
    
    
    int main(){
        int n;
        scanf("%d", &n);
        int size = (2 * n) - 1;
        int A[size][size];
        for(int i = 0; i < size; i++){
    	for(int j = 0; j < size; j++){
    	    A[i][j] = max(max(n - i , n - j) , max(i - n + 2, j - n + 2));
    	}
        }
        for(int i = 0; i < size; i++){
    	for(int j = 0; j < size; j++){
    	    printf("%d ", A[i][j]);
    	}
            printf("\n");
        }
        return 0;
    }
    
  • + 0 comments

    So I am going to leave a hint that helped me out but doesn't completely give it away.

    You can think that you are subtracting out the distance in grid cells that you are away from the closest "wall" or side of the box.

  • + 0 comments

    I was just trying to think wired and it worked lol ( a beginnner) .

    int main(){ int n, x , xt = -1; scanf(" %d",&x); n = 2*x -1; int yt = n; int arr[n][n];

    for(int i = 0; i < n ; i++){

    xt ++;
    yt--;
    for(int j = xt ; j <= yt ; j ++){
        arr[i][j] = x;
        arr[n-1-i][j] = x;
        arr[j][i] = x;
        arr[j][n-1-i] = x;
    }
        if(x ==1)
        break;
    
            x--;
    

    }

    for(int i = 0; i < n; i++){
    
    for(int j = 0 ; j< n ; j ++){
        printf("%d ",arr[i][j]);
    
    }
    printf("\n");
    

    }

  • + 0 comments

    include

    include

    include

    include

    int main() { int n,i; scanf("%d", &n); int size = 2*n-1; int a[size][size];

    int top = 0;
    int bottom=size-1;
    int left=0;
    int right=size-1;
    
    while(top<=bottom && left<=right)
    {
        for(i=left;i<=right;i++)
        {
            a[top][i]=n;
        }
        top++;
        for(i=top;i<=bottom;i++)
        {
            a[i][right]=n;
        }
        right--;
        for(i=right;i>=left;i--)
        {
            a[bottom][i]=n;
        }
        bottom--;
        for(i=bottom;i>=top;i--)
        {
            a[i][left]=n;
        }
        left++;
    
        n--;
    }
    
    
    for(i=0;i<size;i++)
    {
        for(int j=0;j<size;j++)
        {
            printf("%d ",a[i][j]);
        }
        printf("\n");
    }
    

    }