C Programming

Solved Example

Practice Questions

Exercise Question

Program to calculate factorial of a number

Objective

Write a program to find the factorial of a number.

Formula: 5! = 5 * 4 * 3 * 2 * 1

Program / Solution

#include<stdio.h>
int main() {
	int n,i;
	long f;
	printf("Enter any number: ");
	scanf("%d",&n);
	
	f = 1; i =1;
	while(i <= n) {
		f = f * i;
		i++;
	}
	
	printf("Factorial of %d = %ld",n,f);
	return 0;
}

Sample Output

Enter any number: 5
Factorial of 5 = 120