Categories: C++

Pascals triangle

Pascals triangle is a triangular array of binomial coefficients. The numbers outside Pascals triangle are all “0”. These “0s” are very important for the triangular pattern to work to form a triangular array. The triangle starts with a number “1” above, and any new number added below the upper number “1” is just the sum of the two numbers above, except for the edge, which is all “1”.

Program code:

#include <iostream>
using namespace std;

int main()
{
    int r, coeff = 1;

    cout << "Enter number of rows: ";
    cin >> r;

    for(int i = 0; i < r; i++)
    {
        for(int space = 1; space <= r-i; space++)
            cout <<"  ";

        for(int j = 0; j <= i; j++)
        {
            if (j == 0 || i == 0)
                coeff = 1;
            else
                coeff = coeff*(i-j+1)/j;

            cout << coeff << "   ";
        }
        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  

Note: also read about Christmas Tree Pattern

Follow Me

Please follow me to read my latest post on programming and technology if you like my post.

https://www.instagram.com/coderz.py/

https://www.facebook.com/coderz.py

Recent Posts

Generate Parenthesis | Intuition + Code | Recursion Tree | Backtracking | Java

Problem Statement: Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. Example…

2 months ago

Square Root of Integer

Given an integer A. Compute and return the square root of A. If A is…

1 year ago

Build Array From Permutation

Given a zero-based permutation nums (0-indexed), build an array ans of the same length where…

1 year ago

DSA: Heap

A heap is a specialized tree-based data structure that satisfies the heap property. It is…

1 year ago

DSA: Trie

What is a Trie in DSA? A trie, often known as a prefix tree, is…

1 year ago

Trees: Lowest Common Ancestor

What is the Lowest Common Ancestor? In a tree, the lowest common ancestor (LCA) of…

1 year ago