Solving this pattern using abs() [I GOT MY OUTPUT.. CLOSED]

103 views Asked by At

P.S. I'm a beginner and I was trying to find the following output :

         1 
      1  2  3 
   1  2  3  4  5 
1  2  3  4  5  6  7 
   1  2  3  4  5 
      1  2  3 
         1

and here's my try :

#include<stdio.h>
#include<conio.h>

void main() {    
    int n;
    scanf("%d",&n);   

    for(int i=1;(i<=2*n);i++){
        int temp=1,t=2*n-1;     
           
        for(int j=0;j<abs(n-i);j++){
            printf("  ");
        } 
        for(int j=t;j>=abs((2*(i-1))-t);j--) {            
            printf(" %d",temp);
            temp++;
        }                 
    printf("\n");        
    }    
}

as you can see.. I tried my best to remove the i=n condition UNSUCCESSFULLY. or if anyone can provide a more easier way to print the pattern.. I'd my grateful

1

There are 1 answers

2
John Bollinger On

For a given positive input n, you want to print 2 * n - 1 lines.

Now consider the indent of each line: it counts from n - 1 positions down to 0, then back up to n - 1. If you number the lines starting with 1, then that indent is abs(n - line) positions.

The count of numbers to print on each line can be viewed as a function of the indent: the maximum is 2 * n - 1, and each unit of indent reduces that by 2. With a bit of rearrangement, that gives a maximum value to print on each line of 2 * (n - indent) - 1.

That should be sufficient information for you to write a program that prints your pattern, using a single outer loop over all the pattern lines, and employing the abs() function meaningfully. The details are left as the exercise they are meant to be.