-
-
Notifications
You must be signed in to change notification settings - Fork 7.3k
/
pascal_triangle.cpp
75 lines (66 loc) · 1.71 KB
/
pascal_triangle.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
/**
* @file
* @brief Pascal's triangle implementation
*/
#ifdef _MSC_VER
#include <string> // required for Visual C
#else
#include <cstring>
#endif
#include <iomanip>
#include <iostream>
/**
* Print the triangle
* \param [in] arr 2D-array containing Pascal numbers
* \param [in] n depth of Pascal triangle to print
*/
void show_pascal(int **arr, int n) {
for (int i = 0; i < n; ++i) {
for (int j = 0; j < n + i; ++j) {
if (arr[i][j] == 0)
std::cout << std::setw(4) << " ";
else
std::cout << std::setw(4) << arr[i][j];
}
std::cout << std::endl;
}
}
/**
* Print the triangle
* \param [in,out] arr array containing Pascal numbers
* \param [in] n depth of Pascal triangle to print
* \result arr pointer returned
*/
int **pascal_triangle(int **arr, int n) {
for (int i = 0; i < n; ++i) {
for (int j = n - i - 1; j < n + i; ++j) {
if (j == n - i - 1 || j == n + i - 1)
arr[i][j] = 1; // The edge of the Pascal triangle goes in 1
else
arr[i][j] = arr[i - 1][j - 1] + arr[i - 1][j + 1];
}
}
return arr;
}
/**
* main function
*/
int main() {
int n = 0;
std::cout << "Set Pascal's Triangle Height" << std::endl;
std::cin >> n;
// memory allocation (Assign two-dimensional array to store Pascal triangle)
int **arr = new int *[n];
for (int i = 0; i < n; ++i) {
arr[i] = new int[2 * n - 1];
memset(arr[i], 0, sizeof(int) * (2 * n - 1));
}
pascal_triangle(arr, n);
show_pascal(arr, n);
// deallocation
for (int i = 0; i < n; ++i) {
delete[] arr[i];
}
delete[] arr;
return 0;
}