pascal's triangle in c++ through pointer
#include <iostream>
void printPascalTriangle(int n) {
int triangle[n][n];
for (int line = 0; line < n; line++) {
for (int i = 0; i <= line; i++) {
if (i == 0 || i == line)
triangle[line][i] = 1;
else
triangle[line][i] = triangle[line - 1][i - 1] + triangle[line - 1][i];
std::cout << triangle[line][i] << " ";
}
std::cout << std::endl;
}
}
int main() {
int n;
std::cout << "Enter the number of rows for Pascal's triangle: ";
std::cin >> n;
printPascalTriangle(n);
return 0;
}
Step 1: Including necessary header file
The code starts with including the necessary header file iostream
which provides input/output operations in C++.
Step 2: Defining the function printPascalTriangle
The code defines a function printPascalTriangle
which takes an integer parameter n
. This function will be responsible for printing Pascal's triangle.
Step 3: Declaring a 2D array for Pascal's triangle
Inside the printPascalTriangle
function, a 2D array triangle
of size n
by n
is declared. This array will store the values of Pascal's triangle.
Step 4: Generating Pascal's triangle values
The code uses nested loops to generate the values of Pascal's triangle. The outer loop line
iterates from 0 to n-1
to represent each row of the triangle. The inner loop i
iterates from 0 to line
to represent each element in the row.
Step 5: Assigning values to the boundary elements
Inside the inner loop, a conditional statement is used to assign the value 1
to the boundary elements of each row. If i
is equal to 0
or equal to line
, it means the element is at the beginning or end of the row, so it is assigned the value 1
.
Step 6: Calculating values for other elements
For the elements that are not at the boundary, the code calculates their values by adding the corresponding elements from the previous row. The formula used is triangle[line - 1][i - 1] + triangle[line - 1][i]
.
Step 7: Printing the triangle
After calculating the value of each element, it is printed using std::cout
. A space is added after each element. After printing all the elements in a row, a newline is printed using std::endl
.
Step 8: Implementing the main
function
The code defines the main
function which is the entry point of the program. Inside main
, an integer variable n
is declared to store the number of rows for Pascal's triangle. The user is prompted to enter this value using std::cout
. The input is then stored in n
using std::cin
.
Step 9: Calling the printPascalTriangle
function
The printPascalTriangle
function is called with the value of n
as the argument. This will generate and print Pascal's triangle with the specified number of rows.
Step 10: Returning from main
The main
function returns 0
to indicate successful execution of the program.