Pascal triangle using c++

To generate Pascal's triangle using C++, we can use nested loops to calculate and display the values. Here's the code:

#include <iostream>
using namespace std;

int main() {
    int rows;
    cout << "Enter the number of rows: ";
    cin >> rows;

    for (int i = 0; i < rows; i++) {
        int c = 1;
        for (int j = 0; j <= i; j++) {
            cout << c << " ";
            c = c * (i - j) / (j + 1);
        cout << endl;

    return 0;

Let's go through each step of the code:

  1. First, we include the necessary header file iostream to use the input/output stream functionality.

  2. Inside the main() function, we declare a variable rows to store the number of rows in the Pascal's triangle.

  3. We prompt the user to enter the number of rows using the cout object followed by the << operator to display the message. Then, we use the cin object followed by the >> operator to read the value entered by the user and store it in the rows variable.

  4. We start a for loop with the variable i to iterate over each row of the triangle. The loop runs from 0 to rows - 1.

  5. Inside the outer loop, we declare a variable c and initialize it to 1. This variable represents the current value in the triangle.

  6. We start another for loop with the variable j to generate the values in each row. The loop runs from 0 to i.

  7. Inside the inner loop, we display the value of c using the cout object followed by the << operator. We also output a space character to separate the values.

  8. After displaying the value, we update the value of c for the next iteration. We calculate c by multiplying the previous value of c with (i - j) and dividing it by (j + 1). This formula is based on the property of Pascal's triangle where each value is the sum of the two values directly above it.

  9. After the inner loop completes for each row, we move to the next line using cout << endl; to create a new line for the next row.

  10. Finally, we return 0 to indicate successful program execution.