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.|  | 
| GIF Source: Wikipedia | 
Using For Loop for Pascal's triangle
The syntax for For Loop is:
for (intialization;condition;statement update){
statements;
}
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
- Start
- Declare variables i, j, num=1
- Take input (num) for number of rows
- Iterate loop1 for 'num' times
- Iterate loop2 inside loop1 for (num-1) times
- Iterate loop3 inside loop1 after loop2 for 0-i times
- Inside loop3 print num if j == 0 or i ==j
- Inside loop3 else than condition 7 calculate coeffecients according to this formula num=num*(i-j+1)/j
- Print numbers after 3 spaces under loop2
- Print new line under loop1
- End
Flowchart for Pascal's Triangle
 SOURCE CODE FOR PASCALS TRIANGLE
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 in windows only
    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(); } 


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