Skip to main content

ProwessApps

Learn · Practice · Excel

C Program to Calculate Factorial of a given Number.

C Code Example — Function Programs

ADVERTISEMENT

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

  1. Declare the prototype int fact(int).
  2. In main(), read a number and pass it to fact(n).
  3. In the fact() function, run a loop from 1 to x, accumulating the product in f.
  4. Return f back to main() 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 int before fact(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)
ADVERTISEMENT