We help IT Professionals succeed at work.

Creating Pascals Triangle in C, C++.

jonmclean2
jonmclean2 asked
on
Medium Priority
22,452 Views
Last Modified: 2011-09-20
Ok so I have to create a Pascal triangle using a 10*10 Matrix, and the rows and columns displayed will be determined by user input. Obviously the number can't be larger than 10. I need two functions...one that will fill in the correct values to the matrix and another for the user to input the size (less than 10). The matrix should look like this

user input = 4                                                
1      1      1      1
1      2      3      4
1      3      6      10
1      4      10      20

So its a little different than the typical pascal's triangle. This is what I have so far...its the only way I could figure out how to do it, and it prints nicely with a nice triangle shape....but that's not the way "we're supposed to do it." I'm thinking for the first row and column I can create a single loop to place 1's in the top row and another for the first column. Any help is really appreciated.
 
#include<stdio.h>

void main()
{

int line,c,n,x;
void pasc(int);

printf("\n\nEnter the no. of rows: ");
scanf("%d",&line);

printf("\n\n\n");
printf("\nPascal's triangle :\n");

for(x=line-1;x>=0;x--)
            printf("   ");
printf("  1\n\n");

for(n=2;n<=line;n++)
{
      for(c=line-n;c>=1;c--)
            printf("   ");
 pasc(n);
 printf("\n");
}


}


void pasc(int n)
{
      int r;
 long fact(int);
            for(r=0;r<=n;r++)
                  printf("%3ld   ",fact(n)/(fact(n-r)*fact(r)));
}
 
long fact(int v)
{
  if(v==1||v==0)
        return(1);
  else
        return(v*fact(v-1));
}


Comment
Watch Question

Senior Consultant
CERTIFIED EXPERT
Most Valuable Expert 2011
Top Expert 2013
Commented:
Since this is probably a school assignment I will provide a basic algorithm

Declare a 2-dimensional array 11x11
Initialize all cells to 0
Set Array[0][1] to 1
Get the number of rows
Fill row1 - row number
Cell[J][K] = Cell[J-1][K] + Cell[J][K-1]

Print the array

mlmcc

Not the solution you were looking for? Getting a personalized solution is easy.

Ask the Experts
Access more of Experts Exchange with a free account
Thanks for using Experts Exchange.

Create a free account to continue.

Limited access with a free account allows you to:

  • View three pieces of content (articles, solutions, posts, and videos)
  • Ask the experts questions (counted toward content limit)
  • Customize your dashboard and profile

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

OR

Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.