Pascals Triangle Program

Posted by Anoop Nair on September 5, 2017 Tags: C Programs

What is a Pascal's Triangle ?

A triangular array of numbers in which those at the ends of the rows are 1 and each of the others is the sum of the nearest two numbers in the row above.
img


Points to note

  • We have to get number of rows as input from user
  • There will be 3 loops in the program
  • First loop for changing the rows. And we set the value of "value" to 1 on every iteration of this loop The other two loops will be inside this loop.
  • Second loop for printing the preceding spaces which is equal to the number of rows
  • Third loop prints the space between the numbers and the print the Value. After printing the value we set "value" to value = value*(i-k)/(k+1);

Program in C

    
    void PascalsTriangle(int rows);
    void main(){
        int n;
        printf("Enter the total number of rows \n");
        scanf("%d", &n);
        PascalsTriangle(n);
    }

    void PascalsTriangle(int rows){
        int i, j ,k, space = 0;
        space = rows;

        for(i=0; i<= rows ; i++){
            int value = 1;
            for(j= space-(i); j> 0 ; j--){
                printf(" ");
            }
            for(k= 0 ; k<= i ; k++){
                printf(" ");
                printf("%d", value);
                value = value*(i-k)/(k+1);
            }
            printf("\n");
        }
    }
    
  

Output output

Follow the following links to see more examples.


COMMENTS