Home > Software engineering >  Solving this pattern using abs()
Solving this pattern using abs()

Time:03-16

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

CodePudding user response:

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.

CodePudding user response:

I do not really get what detail you want to change.
But I do find all of your code hard to read (not only because of lack of consistent indentation). It gives an impression of "tinkering" with loop conditions and trickery like abs().

I propose to use two outer loops. First for printing increasingly long lines.
Second for printing one fewer decreasingly long lines.

That should allow you to program more straightforward, drop the abs() and get rid of whatever awkward construct you do not like ... even if I still cannot find it in your shown code.

  • Related