C++ Program to Print Pascal’s Triangle

Printing Pascal’s Triangle in C++ is a useful exercise to practice nested loops and understand combinatorial mathematics. Pascal’s Triangle is a triangular array where each entry is the sum of the two directly above it on the previous row. The outer edges of the triangle are populated with ones, and each number inside the triangle is the sum of the two numbers above it.

Here, we’ll write a C++ program that prompts the user to enter the number of rows they want in Pascal’s Triangle, and then outputs the triangle.

C++ Code:

#include <iostream>

using namespace std;

// Function to calculate factorial

int factorial(int n) {

    int fact = 1;

    for (int i = 1; i <= n; ++i) {

        fact *= i;

    }

    return fact;

}

// Function to calculate binomial coefficient (n choose k)

int binomialCoefficient(int n, int k) {

    return factorial(n) / (factorial(k) * factorial(n – k));

}

// Function to print Pascal’s Triangle

void printPascalsTriangle(int rows) {

    for (int n = 0; n < rows; n++) {

        // Printing leading spaces

        for (int space = 1; space <= rows – n; space++) {

            cout << ” “;

        }

        // Calculating and printing the values in each row

        for (int k = 0; k <= n; k++) {

            cout << binomialCoefficient(n, k) << ” “;

        }

        cout << endl;

    }

}

int main() {

    int rows;

    // Asking the user for the number of rows

    cout << “Enter the number of rows for Pascal’s Triangle: “;

    cin >> rows;

    // Printing Pascal’s Triangle

    printPascalsTriangle(rows);

    return 0;

}

Explanation:

  1. Factorial Function:

This function computes the factorial of a given number, used in the calculation of the binomial coefficients.

  1. Binomial Coefficient Function:

Computes the binomial coefficient using the factorial function. The binomial coefficient (𝑛𝑘)(kn​) is crucial for determining the values in Pascal’s Triangle.

  1. Printing Pascal’s Triangle:

    • Outer Loop: Iterates over each row of the triangle.
    • First Inner Loop: Prints spaces to align the numbers properly, creating the triangular shape.
    • Second Inner Loop: Computes and prints each number in the row using the binomial coefficient function.
  2. Main Function:

Takes the number of rows from the user and calls the function to print Pascal’s Triangle.

Program Output:

If the user enters 5 for the number of rows, the output will be:

1

1 1

1 2 1

1 3 3 1

1 4 6 4 1

This triangle visually represents the binomial coefficients, and the values correspond to combinations. Each number represents the number of ways to choose a subset of elements from a larger set where order does not matter. This program provides a foundational understanding of how loops and mathematical functions can be utilized to solve combinatorial problems in C++.

C++ Program to Print Hollow Star Pyramid in a Diamond Shape

Creating a hollow star pyramid in a diamond shape is an interesting exercise to practice nested loops and conditional statements in C++. This pattern involves printing a hollow diamond made of stars (*), where the diamond consists of two parts: the upper pyramid and the inverted lower pyramid, both hollow except for their borders.

Example: Hollow Star Pyramid in a Diamond Shape

This program will prompt the user to enter the number of rows for the upper part of the diamond. The lower part will automatically be generated to match the upper part, creating a symmetrical diamond shape.

C++ Code:

#include <iostream>

using namespace std;

int main() {

    int rows;

    // User inputs the number of rows for the upper part of the diamond

    cout << “Enter the number of rows: “;

    cin >> rows;

    // Print the upper part of the diamond

    for (int i = 1; i <= rows; ++i) {

        // Print leading spaces

        for (int j = 1; j <= rows – i; ++j) {

            cout << ” “;

        }

        // Print stars and hollow spaces

        for (int j = 1; j <= 2 * i – 1; ++j) {

            if (j == 1 || j == 2 * i – 1) {

                cout << “*”;

            } else {

                cout << ” “;

            }

        }

        cout << endl;

    }

    // Print the lower part of the diamond

    for (int i = rows – 1; i > 0; –i) {

        // Print leading spaces

        for (int j = 1; j <= rows – i; ++j) {

            cout << ” “;

        }

        // Print stars and hollow spaces

        for (int j = 1; j <= 2 * i – 1; ++j) {

            if (j == 1 || j == 2 * i – 1) {

                cout << “*”;

            } else {

                cout << ” “;

            }

        }

        cout << endl;

    }

    return 0;

}

Explanation:

  1. Header and Namespace: Includes <iostream> for input and output operations and uses the std
  2. Input: The user specifies the number of rows for the upper half of the diamond.
  3. Upper Diamond:
    • Outer Loop: Manages the rows of the upper pyramid.
    • First Inner Loop: Controls the spaces before the stars begin, decreasing as the rows increase.
    • Second Inner Loop: Handles the printing of stars and hollow spaces. Stars are printed only at the edges (j == 1 or j == 2 * i – 1), leaving the rest as spaces.
  4. Lower Diamond:
    • Outer Loop: Manages the rows of the inverted lower pyramid.
    • First Inner Loop: Similar to the upper part but for spacing, it increases as you move deeper into the lower part.
    • Second Inner Loop: Similar to the upper part in terms of star placement and hollow spaces.

Program Output:

If the user inputs 4 for the number of rows, the output will be:

*

* *

*   *

*     *

*   *

* *

*

This pattern creates a visually appealing hollow diamond using nested loops and conditional checks to determine where to print stars and spaces, illustrating how to manipulate console output effectively in C++.

C++ Program to Print Inverted Hollow Star Pyramid Pattern

Creating an inverted hollow star pyramid pattern in C++ is an excellent exercise to deepen your understanding of loops and conditional statements. This pattern features an inverted pyramid where only the border of the pyramid is marked with stars (*), leaving the inside hollow or empty.

Example: Inverted Hollow Star Pyramid Pattern

This program will display an inverted hollow star pyramid based on the number of rows specified by the user. The top row will be completely filled with stars, and subsequent rows will only have stars at the borders, with the inner part being hollow until the last row which has just one star.

C++ Code:

#include <iostream>

using namespace std;

int main() {

    int rows;

    // User inputs the number of rows for the pyramid

    cout << “Enter the number of rows: “;

    cin >> rows;

    // Print the inverted hollow pyramid

    for (int i = rows; i > 0; –i) {

        // Print leading spaces

        for (int j = 0; j < rows – i; ++j) {

            cout << ” “;

        }

        // Print stars and hollow spaces

        for (int j = 1; j <= 2 * i – 1; ++j) {

            if (j == 1 || j == 2 * i – 1 || i == rows) {

                cout << “*”; // Print star at borders and top row

            } else {

                cout << ” “; // Print space inside the pyramid

            }

        }

        cout << endl;

    }

    return 0;

}

Explanation:

  1. Header and Namespace: The program includes <iostream> for input/output operations and uses the std
  2. Input: The user is prompted to enter the number of rows for the pyramid. This number determines the height of the inverted pyramid.
  3. Loop for Rows:
    • Outer Loop: Runs from the specified number of rows down to 1, handling each row of the pyramid.
    • First Inner Loop: Manages the spaces before the stars begin on each row. These spaces increase as you move to lower rows (which are visually higher in the inverted pyramid).
    • Second Inner Loop: Manages the printing of stars and hollow spaces. Stars are printed at the first and last positions (j == 1 or j == 2 * i – 1) and across the entire top row (i == rows). The rest is filled with spaces.

Program Output:

Assuming the user inputs 5 for the number of rows, the output will be:

*********

*     *

*   *

* *

*

This program uses a combination of loops and conditional logic to create an appealing pattern. Such exercises are useful for practicing how to manipulate output based on the location within the loops, a key skill in developing more complex algorithms and applications in C++.

error: Content is protected !!