Skip to main content

ProwessApps

Learn · Practice · Excel

Pascal's Triangle

C++ Code Example — Pattern Programs

ADVERTISEMENT

Pascal's Triangle

Objective

Write a C++ program to print Pascal's Triangle using a factorial function.

Algorithm / Approach

  1. Create a fact() function to calculate factorials.
  2. In main(), use nested loops to print spaces to center the triangle.
  3. Use an inner loop c to calculate and print the combination formula: fact(i) / (fact(c) * fact(i - c)).
main.cpp
#include<iostream>
using namespace std;
int fact(int x) {
 int res = 1;
 for(int i = 1; i< x; i++) {
  res = res*i;
 }
 return res;
}
int main() {
 int n;
 cout<<"Enter the value for N: ";
 cin>>n;
 for(int i=0; i<=n; i++) {
  for(int c = 0; c <= (n-i-2); c++) {
   cout<<" ";
  }
 for(int c =0; c< i; c++) {
  cout<< fact(i)/(fact(c)*fact(i-c));
 }
  cout<< endl;
 }
return 0;
}

Expected Output

1
  1 1
 1 2 1
1 3 3 1

Explanation of the Program

  • Pascal's Triangle is a triangular array of binomial coefficients. Every number in the triangle can be mathematically calculated using the combinations formula (nCr).
  • Note on the provided code: The fact function contains a logical bug. The loop condition is i &lt; x instead of i &lt;= x. This calculates the factorial incorrectly for larger numbers, causing the triangle values to break!

Complexity

Time Complexity O(n^3) - Nested loops calling a factorial loop.
Space Complexity O(1)

Common Mistakes

  • Writing the factorial loop as i &lt; x instead of i &lt;= x. For example, calculating 3! (which is 3 * 2 * 1 = 6) with &lt; will stop at 2, returning 2 * 1 = 2.
ADVERTISEMENT