-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpascaltriangle.c
80 lines (65 loc) · 1.6 KB
/
pascaltriangle.c
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
76
77
78
79
80
/*
* AUTHOR: Khaled Mohammad
* DATED: September 5, 2015.
* git: https://github.com/itskhaledmohammad
* twitter: https://twitter.com/itskhaledmd (@itskhaledmd)
*
* This is a challenge where you have to printout the the
* Pascal Triangle.
* Wiki: https://en.wikipedia.org/wiki/Pascal%27s_triangle
*
*/
#include <stdio.h>
#include <stdlib.h>
// Macros.
#define SPACES " "
#define COMBERR 56789
#define FACTERR 56777
/*
* This function calculates
* the factorial of any number.
*/
int mathFact(int number)
{
int fact = 1;
for(int i = number; i > 0; i--)
fact = fact * i;
return fact;
}
/*
* This function calculates
* the combination of any given values of n and r.
* example: 4C4
*/
int mathComb(int n, int r)
{
// Initialization.
int result = 0;
// Checking if the input is correct.
if (n < r)
return COMBERR;
// Perform the combination formula.
// Formula: n! / r!(n - r)!
result = mathFact(n) / (mathFact(n - r) * mathFact(r));
// Return the result.
return result;
}
int main(void)
{
// Initialization.
int height = 0, rows = 0 ,pos = 0,spaces = 0;
// Taking our input of the height.
printf("Type the height of the pyramid: ");
scanf("%d", &height);
// Make our pyramid.
for(rows = 0; rows < height; rows++){
// Making things pretty.
for(spaces = height - rows;spaces > 0; spaces--)
printf(SPACES); // Print the spaces.
// Print in the numbers according to their position.
for(pos = 0; pos <= rows; pos++)
printf("%d ",mathComb(rows, pos));
printf("\n");
}
printf("\n"); // Printing a new line.Just making things pretty.
}