summary refs log tree commit diff stats
path: root/assignments/27-fac-rec.c
diff options
context:
space:
mode:
Diffstat (limited to 'assignments/27-fac-rec.c')
-rw-r--r--assignments/27-fac-rec.c52
1 files changed, 52 insertions, 0 deletions
diff --git a/assignments/27-fac-rec.c b/assignments/27-fac-rec.c
new file mode 100644
index 0000000..13f00d3
--- /dev/null
+++ b/assignments/27-fac-rec.c
@@ -0,0 +1,52 @@
+#include <stdio.h>
+
+int fact(int n)
+{
+	if (n == 0)
+		return 1;
+	else
+		return n * fact(n - 1);
+}
+
+int main(void)
+{
+	int n;
+	printf("To calculate the factorial of a given number\n\n");
+	printf("Enter a number: ");
+	scanf("%d", &n);
+	if (n < 0) {
+		printf("Invalid input, must be greater than -1\n");
+		return 0;
+	}
+	printf("%d! = %d\n", n, fact(n));
+	return 0;
+}
+
+/*
+Output:
+Set 1:
+To calculate the factorial of a given number
+
+Enter a number: -1
+Invalid input, must be greater than zero
+
+Set 2:
+To calculate the factorial of a given number
+
+Enter a number: 0
+0! = 1
+
+Set 3:
+To calculate the factorial of a given number
+
+Enter a number: 5
+5! = 120
+
+Set 4:
+To calculate the factorial of a given number
+
+Enter a number: 10
+10! = 3628800
+
+*/
+