TheAlgorithms/C++
1.0.0
All the algorithms implemented in C++
Loading...
Searching...
No Matches
pascal_triangle.cpp
Go to the documentation of this file.
1
5
#ifdef _MSC_VER
6
#include <string>
// required for Visual C
7
#else
8
#include <cstring>
9
#endif
10
#include <iomanip>
11
#include <iostream>
12
18
void
show_pascal
(
int
**arr,
int
n) {
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
}
29
36
int
**
pascal_triangle
(
int
**arr,
int
n) {
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
}
48
52
int
main
() {
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
}
pascal_triangle
int ** pascal_triangle(int **arr, int n)
Definition
pascal_triangle.cpp:36
show_pascal
void show_pascal(int **arr, int n)
Definition
pascal_triangle.cpp:18
main
int main()
Definition
pascal_triangle.cpp:52
others
pascal_triangle.cpp
Generated by
1.12.0