Prakhar Sharma
Prakhar Sharma

Reputation: 21

Correct Alignment of Numbers in PASCAL TRIANGLE

I made a program for making a pascal triangle and for the input of numbers ( rows ) > 5 , there is an alignment problem i.e for ncr > 10. Help me out please. I have included the images for output of the program.

Output Image

#include<stdio.h>
int factorial(int number)
{   
    int fact=1;
    for(int i=1; i<=number; ++i )
    {
        fact*=i;
    }
    return fact;
}

int ncr(int n, int r)
{
    int ncr;
    int fact1=factorial(n);
    int fact2=factorial(n-r);
    int fact3=factorial(r);
    ncr = fact1 /(fact2 * fact3);
    return ncr; 
}


int main()
{
    int rows;
    printf("enter the number of rows :\n");
    scanf("%d",&rows);
    for(int n=0; n<rows; n++)
    {
        for(int i=1; i<=rows-n; i++)
        {
            printf(" ");
        }
        for(int r=0; r<=n; r++)
        {
            printf("%d ",ncr(n,r));
        }   
        printf("\n");
    }
    return 0;   
}

Upvotes: 0

Views: 448

Answers (3)

patel apurv
patel apurv

Reputation: 19

If you use

printf ("Width trick: %*d \n", 5, 10);

this will add 5 more spaces before the digit value.

Upvotes: 0

v7d8dpo4
v7d8dpo4

Reputation: 1399

printf can take a precision before the formatter. Change printf("%d ",ncr(n,r)); to printf("%3d ",ncr(n,r)); to make the numbers 3 characters wide. Also change printf(" "); to printf(" ");.

Upvotes: 1

Rishikesh Raje
Rishikesh Raje

Reputation: 8614

You can change the inner loop like this

for(int i=1; i<=rows-n; i++)
{
   printf("  ");    // Note the extra space
}
for(int r=0; r<=n; r++)
{
   printf("%3d ",ncr(n,r)); // Changed to %3d
}  

This will work upto 9 rows. If you want it to work for more rows, you can add another space in the first printf and change the second printf to %5d

Upvotes: 1

Related Questions