TheAlgorithms/C++ 1.0.0
All the algorithms implemented in C++
Loading...
Searching...
No Matches
pascal_triangle.cpp File Reference

Pascal's triangle implementation. More...

#include <cstring>
#include <iomanip>
#include <iostream>
Include dependency graph for pascal_triangle.cpp:

Go to the source code of this file.

Functions

void show_pascal (int **arr, int n)
 
int ** pascal_triangle (int **arr, int n)
 
int main ()
 

Detailed Description

Pascal's triangle implementation.

Definition in file pascal_triangle.cpp.

Function Documentation

◆ main()

int main ( void )

main function

Definition at line 52 of file pascal_triangle.cpp.

52 {
53 int n = 0;
54
55 std::cout << "Set Pascal's Triangle Height" << std::endl;
56 std::cin >> n;
57
58 // memory allocation (Assign two-dimensional array to store Pascal triangle)
59 int **arr = new int *[n];
60 for (int i = 0; i < n; ++i) {
61 arr[i] = new int[2 * n - 1];
62 memset(arr[i], 0, sizeof(int) * (2 * n - 1));
63 }
64
65 pascal_triangle(arr, n);
66 show_pascal(arr, n);
67
68 // deallocation
69 for (int i = 0; i < n; ++i) {
70 delete[] arr[i];
71 }
72 delete[] arr;
73
74 return 0;
75}
int ** pascal_triangle(int **arr, int n)
void show_pascal(int **arr, int n)

◆ pascal_triangle()

int ** pascal_triangle ( int ** arr,
int n )

Print the triangle

Parameters
[in,out]arrarray containing Pascal numbers
[in]ndepth of Pascal triangle to print
Returns
arr pointer returned

Definition at line 36 of file pascal_triangle.cpp.

36 {
37 for (int i = 0; i < n; ++i) {
38 for (int j = n - i - 1; j < n + i; ++j) {
39 if (j == n - i - 1 || j == n + i - 1)
40 arr[i][j] = 1; // The edge of the Pascal triangle goes in 1
41 else
42 arr[i][j] = arr[i - 1][j - 1] + arr[i - 1][j + 1];
43 }
44 }
45
46 return arr;
47}

◆ show_pascal()

void show_pascal ( int ** arr,
int n )

Print the triangle

Parameters
[in]arr2D-array containing Pascal numbers
[in]ndepth of Pascal triangle to print

Definition at line 18 of file pascal_triangle.cpp.

18 {
19 for (int i = 0; i < n; ++i) {
20 for (int j = 0; j < n + i; ++j) {
21 if (arr[i][j] == 0)
22 std::cout << std::setw(4) << " ";
23 else
24 std::cout << std::setw(4) << arr[i][j];
25 }
26 std::cout << std::endl;
27 }
28}