C PROGRAM FOR PASCAL'S TRIANGLE WITH FLOWCHART AND ALGORITHM

C PROGRAM FOR PASCAL'S TRIANGLE

Background for Pascal's Triangle

Pascal's Triangle is a special triangle formed by the triangular arrangement of numbers. This arrangement is done in such a way that the number in the triangle is the sum of the two numbers directly above it. The first number starts with 1. Refer to this image.
visual representation of pascal's triangle
 This triangle is named after the french mathematician Blaise Pascal but this triangle have been in existence and was being studied by other ancient mathematicians of India, China, Italy, Persia, and Germany before him.

Using For Loop for Pascal's triangle

The syntax for For Loop is:

for (intialization;condition;statement update)
{
         statements;
}

Flowchart for For Loop 

flowchart for for loop


But single loop is not enough to build a pascal's triangle since there are elements in vertical and horizontal axes. So, we will use nested For Loops i.e For Loop inside For Loop to calculate elements in each row.

Algorithm for Pascal's Triangle

  1. Start
  2. Declare variables i, j, num=1
  3. Take input (num) for number of rows
  4. Iterate loop1 for 'num' times
  5. Iterate loop2 inside loop1 for (num-1) times
  6. Iterate loop3 inside loop1 after loop2 for  0-i times
  7. Inside loop3 print num if j == 0 or i ==j
  8. Inside loop3 else than condition 7 calculate coeffecients according to this formula num=num*(i-j+1)/j
  9. Print numbers after 3 spaces under loop2
  10. Print new line under loop1
  11. End

Flowchart for Pascal's Triangle

flowchart for pascal's triangle

 SOURCE CODE

PROGRAM THAT CONSTRUCTS PASCAL'S TRIANGLE FOR "N" ROWS

#include<stdio.h>
#include <stdlib.h>
int main()
{
    int i,j,num=1,n,space;
    scanf("%d",&n);  //takes input for number of rows
    system("cls");   //clears screen
    for (i=0;i<n;i++){  //loop for rows
        for (space=i;space<n;space++){ //space's loop
            printf("  ");
        }
        for (j=0;j<=i;j++){  //loop for coefficient
            if (j == 0 || i == j)//checks for position
                num=1;
            else
                num = num*(i-j+1)/j;
        printf("   %d",num);   //prints coefficient
        }
        printf("\n");  //prints new line
    }  getch(); }

Comment down if you have any problems

Post a Comment

1 Comments

  1. great job! this explains well about the way c programs are made to program the pascals triangle.Loved it !

    ReplyDelete