-
Notifications
You must be signed in to change notification settings - Fork 131
Expand file tree
/
Copy pathlab2_2.c
More file actions
35 lines (28 loc) · 664 Bytes
/
lab2_2.c
File metadata and controls
35 lines (28 loc) · 664 Bytes
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
#include <stdio.h>
/*
Task:
Write a function `long long factorial(int n)` that computes n!
using a loop (not recursion).
In main():
- Ask user for an integer n
- If n is negative, print an error and exit
- Otherwise, call factorial and print the result
*/
long long factorial(int n) {
long long res = 1;
for (int i=1; i<=n; i++) {
res *= i;
}
return res; // placeholder
}
int main(void) {
int n;
printf("Enter a non-negative integer n: ");
scanf("%d", &n);
if (n<0) {
printf("Error\n");
} else {
printf("The result is: %d\n", factorial(n));
}
return 0;
}