Printing Pattern Using Loops

Sort by

recency

|

1055 Discussions

|

  • + 0 comments
    • i have used some conditions and a variable which is inc-dec .. how do you see this solution?

    • int a;

    • int i,j;
    • scanf("%d", &a);
    • int n=(a*2)-1;
    • for(i=1;i<=n;i++)
    • {
    • for(j=1;j<=n;j++)
    • {
    • printf("%d ",((i-j>0&&i<(n/2)+1)||(i+j=(n/2)+1))?a--:((i-j<0 &&i>(n/2)+1)||(i+j>n+1 && i<=(n/2)+1))?++a:a);
    • }
    • printf("\n");
    • }
  • + 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;
    

    }