#include <iostream>
using namespace std;
int main() {
int rows, coef = 1;
cout << "Enter the number of rows you want to print: ";
cin >> rows;
for(int i = 0; i < rows; i++) {
for(int space = 1; space <= rows - i; space++) {
cout << " ";
}
for(int j = 0; j <= i; j++) {
if(j == 0 || i == 0) {
coef = 1;
} else {
coef = coef * (i - j + 1) / j;
}
cout << coef << " ";
}
cout << endl;
}
return 0;
}
//===========
OUTPUT:
Enter the number of rows you want to print: 6
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
Explanation:
We start by including the necessary header files and declaring our main function.
We then declare two integer variables,
rowsandcoef, which will be used to store the number of rows to be printed and the coefficient value respectively.We prompt the user to enter the number of rows they want to print using
coutandcinstatements.We use two nested for loops to print the triangle. The outer loop iterates over the rows, while the inner loop iterates over the columns.
The first inner loop prints the necessary number of spaces to align the triangle properly.
The second inner loop calculates the coefficient values using the formula
(i-j+1)/jfor each element in the row and prints it.Finally, we print a newline character after each row to start a new line.
Notes:
- Pascal's Triangle is a triangular array of numbers in which the first and last numbers of each row are 1 and the other numbers are the sum of the two numbers immediately above it.
- The number of rows in Pascal's Triangle is user-defined in this program.
- The program uses a mathematical formula to calculate the coefficient values for each element in the row.
- The program uses nested for loops to print the triangle, with the outer loop iterating over the rows and the inner loop iterating over the columns.
- The program prints spaces to align the triangle properly.
- The program uses the using namespace std statement to avoid the need for fully qualified names when using standard library functions like cout and cin.
No comments:
Post a Comment