C Program to Calculate Factorial of a given Number.
Objective
Write a C program to calculate the factorial of a number using a user-defined function.
Algorithm / Approach
- Declare the prototype
int fact(int). - In
main(), read a number and pass it tofact(n). - In the
fact()function, run a loop from 1 tox, accumulating the product inf. - Return
fback tomain()and print it.
main.c
#include<stdio.h>
int fact(int);
int main(){
int n,res;
printf("Enter number: ");
scanf("%d",&n);
res = fact(n);
printf("Factorial : %d",res);
return 0;
}
int fact(int x){
int i, f=1;
for(i=1; i<=x; i++){
f = f*i;
}
return f;
}
Expected Output
Enter a Number : 5 Factorial = 120
Explanation of the Program
- Functions allow you to break down large programs into smaller, reusable blocks of code.
- The
intbeforefact(int x)indicates the "Return Type". It promises that when this function finishes its work, it will hand back an integer value to whoever called it.
Complexity
Time Complexity
O(n) - Where n is the input number.
Space Complexity
O(1)