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:
First, we include the necessary header file
iostream
to use the input/output stream functionality.Inside the
main()
function, we declare a variablerows
to store the number of rows in the Pascal's triangle.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 thecin
object followed by the>>
operator to read the value entered by the user and store it in therows
variable.We start a
for
loop with the variablei
to iterate over each row of the triangle. The loop runs from 0 torows - 1
.Inside the outer loop, we declare a variable
c
and initialize it to 1. This variable represents the current value in the triangle.We start another
for
loop with the variablej
to generate the values in each row. The loop runs from 0 toi
.Inside the inner loop, we display the value of
c
using thecout
object followed by the<<
operator. We also output a space character to separate the values.After displaying the value, we update the value of
c
for the next iteration. We calculatec
by multiplying the previous value ofc
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.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.Finally, we return 0 to indicate successful program execution.