Google+ Program to Display Pascal Triangle in c++[how to] - CodieeHome
“Any fool can write code that a computer can understand. Good programmers write code that humans can understand.”
__

Pascal Triangle

Goal:- Display a Pascal Triangle.

Method Used:- By using Property of Pascal triangle.

Explanation: Pascal triangle is a triangular array which contains Binomial coefficients. 

The rows of pascal triangle starts with n=0.In construction of triangle first and last element of each row is kept equal to one.
For calculating value of other elements we simply add the number above and to the left with the number above and to the right.
If we have i rows and n columns in a pascal triangle then it follows the following property-

               a[i][j]= a[i-1][k-1]+a[i-1][k] where (i!=j & j!=0)
                  if i=j or j=0 then a[i][j]=1.

Program:-


#include<iostream>
using namespace std;
#include<conio.h>
int main()
 {
    int a[10][10],k,i,j,count,m;
     cout<<"How many levels you want to have ";
     cin>>k;
     for(i=0;i<k;i++)
       {
          for(j=0;j<=i;j++)
           {
                if(i==j || j==0)
                  a[i][j]=1;
                else
                  a[i][j]=a[i-1][j-1]+a[i-1][j];
           }    
      }    
       count=k-1;
       
       for(i=0;i<k;i++)
       {
        for(m=0;m<count;m++)
           {
              cout<<"\t";
           }  
          for(j=0;j<=i;j++)
           {
             cout<<"|"<<a[i][j]<<"|\t\t";
              }
             cout<<"\n";  
             count--;  
             }
             getch();
             return 0;
}      

Output:-

     

 If you want to share more information about topic discussed above or find anything incorrect Please do comments.  

0 comments:

Post a Comment

 
Top