Pascal's triangle
Pascal's triangle is a mathematical triangle named after French mathematician Blaise Pascal. This triangle consists of different numbers and has infinite numbers of rows. The main arithmetic followed to create this triangle is the addition. The number of elements in a row is equal to the row on which the elements are placed on. The following triangle is the example of Pascal's triangle having five rows:
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
The first row in triangle contains only one number i.e 1. In the second row, the first element 1 is the sum of its top left and right element i.e 0 and 1. Similarly, the second element 1 of the second row is the sum of its top left and right element i.e 1 and 0. In the third row first element is 1 which is the sum of its top left and right numbers i.e 0 and 1. The second element on the third row is 2 which is the sum of its top left and right number i.e 1 and 1. A similar process is carried out to find elements in other rows of the triangle.
Write a program in C++ to print Pascal's triangle with n number of rows.
We will ask the user about the number of row s/he wants to print.We will use a matrix to create the triangle.The first and last element of each row is declared as 1.The the elements a[i][j] in between are calculated by the sum of top left a[i-1][j-1] and top right element a[i-1][j] as:
a[i][j]=a[i-1][j-1]+a[i-1][j];
Then we print the matrix.
a[i][j]=a[i-1][j-1]+a[i-1][j];
Then we print the matrix.
Program
#include<iostream.h>
#include<conio.h>
void main()
{
int i,j,k,n,x,y,z;
int a[20][20];
clrscr();
cout<<"Enter a number of rows= ";
cin>>n;
for(k=1;k<=n;k++) //Loop for declaration of first and last element of row as 1
{
a[k][1]=1;
a[k][k]=1;
}
for(i=3;i<=n;i++) //Loop for calculation of middle elements of row
{
for(j=2;j<i;j++)
{
a[i][j]=a[i-1][j-1]+a[i-1][j];
}
}
for(x=1;x<=n;x++) //Loop for printing of matrix
{
for(z=n;z>x;z--) //Loop for manipulation of spaces
{
cout<<" ";
}
for(y=1;y<=x;y++)
{
cout<<" "<<a[x][y];
}
cout<<"\n";
}
getch();
}
#include<conio.h>
void main()
{
int i,j,k,n,x,y,z;
int a[20][20];
clrscr();
cout<<"Enter a number of rows= ";
cin>>n;
for(k=1;k<=n;k++) //Loop for declaration of first and last element of row as 1
{
a[k][1]=1;
a[k][k]=1;
}
for(i=3;i<=n;i++) //Loop for calculation of middle elements of row
{
for(j=2;j<i;j++)
{
a[i][j]=a[i-1][j-1]+a[i-1][j];
}
}
for(x=1;x<=n;x++) //Loop for printing of matrix
{
for(z=n;z>x;z--) //Loop for manipulation of spaces
{
cout<<" ";
}
for(y=1;y<=x;y++)
{
cout<<" "<<a[x][y];
}
cout<<"\n";
}
getch();
}
Output
PRINTING OF PASCAL'S TRIANGLE |
Explanation
In the above program, the user wanted to print Pascal's triangle with 5 number of rows. The numbers were stored in an array and addition was performed as per the method discussed above. Pascal's triangle with 5 rows was displayed on the output screen.
Fact about C++
The output screen(i.e black in color) in C++ programming is also called Console screen.
No comments:
Post a Comment