Pascal's triangle is a triangular array of binomial coefficients in which each element is the sum of 2 numbers directly above it. This triangular array is made up of summing adjacent elements in preceding rows.
Note: It is named after French scientist and mathematician, Blaise Pascal.
The formula to calculate the number of ways in which
From the figure below, visualize how the pascal formula helps to create a pascal triangle:
In a pascal triangle, the number of entries are always equal to its row number or line number. In the figure below, the total number of rows is 11 so in the last row, we get 11 entries. The left most and right most numbers of each row are always 1.
Here, we implement the pascal triangle in C++. For implementation, we use nested loops. The outer loop works for row indentation. The first inner loop creates spaces so that we get a proper indentation of the triangle. The second inner loop calculates the value of num
. We use a binomial coefficient formula to get desired values of the pascal triangle.
#include <iostream>using namespace std;//driver codeint main() {int rows=5; //no of rows in pascal trianglefor(int i=0;i<rows;i++) { //outer loopint num=1;for(int j=0;j<rows-i-1;j++){ //loop for spacescout<<" ";}for(int k=0;k<=i;k++){ //loop for printing numberscout<<num<<" ";num=num*(i-k)/(k+1); //formula of pascal triangle}cout<<endl;}return 0;}
rows
, to get the number of rows. Next, we create an outer for
loop in which num
is initialized. Here, num
is a pascal number that stores values to be printed in Pascal's triangle.for
loop to get spaces between the numbers to create a perfect pascal trianglefor
loop to print the numbers on a screen. Note: Want to know about the triangle inequality theorem? Click here