summary refs log tree commit diff stats
path: root/assignments/17-pascal-triangle.c
diff options
context:
space:
mode:
authorsmlckz <smlckz@college>2021-12-22 14:56:13 +0530
committersmlckz <smlckz@college>2021-12-22 14:56:13 +0530
commitb73983c3717642ca10e7cfe93d97609adc377da9 (patch)
treea6e9fe4c27e3caa215f8aefa9265fb52f6de4375 /assignments/17-pascal-triangle.c
downloadcollege-b73983c3717642ca10e7cfe93d97609adc377da9.tar.gz
backup
Diffstat (limited to 'assignments/17-pascal-triangle.c')
-rw-r--r--assignments/17-pascal-triangle.c52
1 files changed, 52 insertions, 0 deletions
diff --git a/assignments/17-pascal-triangle.c b/assignments/17-pascal-triangle.c
new file mode 100644
index 0000000..24047c6
--- /dev/null
+++ b/assignments/17-pascal-triangle.c
@@ -0,0 +1,52 @@
+#include <math.h>
+#include <stdio.h>
+#include <stdlib.h>
+
+static int count_digits(double n)
+{
+	return floor(log10(n)) + 1;
+}
+
+static double factorial(double n)
+{
+	return tgamma(n + 1);	
+}
+
+static double comb(long n, long r)
+{
+	return factorial(n) / (factorial(r) * factorial(n - r));
+}
+
+int main(void)
+{
+	int i, j, k, h, l, *arr, *p;
+	size_t n;
+	printf("To Print the Pascal's Triangle\n\n");
+	printf("Enter a height: ");
+	scanf("%d", &h);
+	l = count_digits(comb(h, h / 2));
+	arr = malloc((h + 3) * sizeof(int));
+	if (arr == NULL) {
+		printf("Insufficient memory.\n");
+		return 0;
+	}
+	arr[0] = 1;
+	arr[1] = 0;
+	n = 1;
+	for (i = 1; i <= h + 1; i++) {
+		for (k = 1; k <= (h - i + 1) * l; k++) {
+			printf(" ");
+		}
+		for (k = 0; k < n; k++) {
+			printf("%- *d ", l + 1, arr[k]);
+		}
+		printf("\n");
+		arr[k+1] = 0;
+		for (n++; k > 0; k--) {
+			arr[k] += arr[k-1];
+		}
+	}
+	free(arr);
+	return 0;
+}
+