What is Pascal's triangle?

Overview

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.

Pascal's formula

The formula to calculate the number of ways in which rr objects can be chosen from nn objects is given below:

From the figure below, visualize how the pascal formula helps to create a pascal triangle:

Working

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.

Pascal triangle
Pascal triangle

Implementation

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 code
int main() {
int rows=5; //no of rows in pascal triangle
for(int i=0;i<rows;i++) { //outer loop
int num=1;
for(int j=0;j<rows-i-1;j++){ //loop for spaces
cout<<" ";
}
for(int k=0;k<=i;k++){ //loop for printing numbers
cout<<num<<" ";
num=num*(i-k)/(k+1); //formula of pascal triangle
}
cout<<endl;
}
return 0;
}

Explanation

  • Line 6–8: We initialize the variable, 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.
  • Line 9–11: We create an inner for loop to get spaces between the numbers to create a perfect pascal triangle
  • Line 12–16: We create a second inner for loop to print the numbers on a screen.

Note: Want to know about the triangle inequality theorem? Click here

Copyright ©2024 Educative, Inc. All rights reserved