Printing Pattern Using Loops

Sort by

recency

|

1054 Discussions

|

  • + 0 comments

    At first, I created the matrix for the first quadrant and used a lot of lines to print it in order and reverse order. But later, I saw that the AI's code was much more concise. That's when I realized the pattern: the value of each element is n - d, where d is the minimum distance from the element to the matrix boundary.

  • + 0 comments

    Here is Printing patterns using loops solution in c - https://programmingoneonone.com/hackerrank-printing-pattern-using-loops-in-c-solution.html

  • + 0 comments

    include

    include

    include

    include

    int main() {

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

    }

  • + 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;
    }