Printing Pattern Using Loops

  • [deleted]
    + 3 comments

    With this kind of problems, I always think about separating it into several shapes. Here's what I do with this problem:

    void print_upper_part( int n )
    {
        int i,j,k,m;
        
        for( i = n; i >= 1 ; i-- ){
            // generate left triangle of numbers
            // the shape is somethin like:
            // *
            // **
            // ***
            // ****
            // *****
            for( j = n; j >= i; j-- ){
                printf("%d ",j);
            }
            // use the value before the last decrement
            j++;
            // generate the reverse pyramid using value of j
            // the shape is something like:
            // *******
            //  *****
            //   ***
            //    *
            for( k = 1; k <= (2*j) - 3; k++  ){
                printf("%d ",j);
            }
            // avoid printing 1 again since 1 has been printed at the left triangle
            j = j == 1 ? 2 : j;
            // generate right triangle of numbers
            // the shape is somethin like:
            //     *
            //    **
            //   ***
            //  ****
            // *****
            for( m = j; m <= n; m++ ){
                printf("%d ",m);
            }
            printf("\n");
        }
    }
    
    void print_lower_part( int n )
    {
        int i,j,k,m;
        
        for( i = 2; i <= n ; i++ ){
            // generate left triangle of numbers
            // the shape is somethin like:
            // *****
            // ****
            // ***
            // **
            // *
            for( j = n; j >= i; j-- ){
                printf("%d ",j);
            }
            // use the value before the last decrement
            j++;
            // generate the pyramid using value of j
            // the shape is something like:
            //    *  
            //   ***
            //  *****
            // *******
            for( k = 1; k <= (2*j) - 3; k++ ){
                printf("%d ",j);
            }
            // generate right triangle of numbers
            // the shape is somethin like:
            // *****
            //  ****
            //   ***
            //    **
            //     *
            for( m = i; m <= n; m++ ){
                printf("%d ",m);
            }
            printf("\n");
        }
    }