C++ Program to Print Pascal's Triangle
C++ program to print pascal triangle is provided on this page.
Pascal's Triangle is triangular array of binomial coefficients that arises in probability theory, combinations and algebra.
This pascal's triangle is named after blaise pascal but many mathematicians studied it centuries before him in india, persia, china, germany and italy.
Simply put pascal's triangle is triangle or pyramid of numbers.
When you understand how the numbers are arranged you understand pascal's triangle and hence the logic to write c++ program for the same.
Here is visual representation of pascal's triangle.
If you observe, you will notice, for each new row the new elements that appear are sum of left and right parts.
C++ program to print Pascal triangle
This C++ program accepts the number of rows from user and prints the pascal's triangle based on rows.
Here is the source code for c++ program to print pascal triangle.
/* Print Pascal's triangle in c++ */
#include<iostream>
using namespace std;
int main()
{
int rows;
cout << "Enter the number of rows : ";
cin << rows;
for (int i = 0; i < rows; i++)
{
int val = 1;
for (int j = 1; j < (rows - i); j++)
{
cout << " ";
}
for (int k = 0; k <= i; k++)
{
cout << " " << val;
val = val * (i - k) / (k + 1);
}
count << endl << endl;
}
cout << endl;
return 0;
}
Output:
Enter number of rows: 6 1 1 1 1 2 1 1 3 3 1 1 4 6 4 1 1 5 10 10 5 1
Comments
Post a Comment