Example HTML page

C Program to find the factorial of a given number

In this section, i am going to write a “C” program to find the factorial of a given number using functions (non-recursive)

The factorial of a number is obtained as follows:

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

or

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

I choose the second way in this program.

The logic here is Start from “1”and increment it by ‘1’ and multiply with the previous number until the increment reaches to the given number.

In other words

1

increment by 1 ==> 1+1 ==> 2

now ‘2’ is multiplied with previous number 1.

1*2

increment by 1 ==> 2+1 ==> 3

now 3 is multiplied with previous result

3 * 2 ==>6   or it may also taken as 1 * 2* 3.

This process is continued up to ‘n’  if user enters ‘n’ as ‘5’ , then 1 *2 * 3* 4 * 5 = 120.

#include<stdio.h>
int factorial(int);
int main()
{
	int n,fact;
	printf("Eneter a number:\n");
	scanf("%d",&n);
	
	fact=factorial(n);
	printf("Factorial of %d is %d",n,fact);
	
	return 0;
}
int factorial(int x)
{
	int f=1,i;
	
	for(i=1;i<=x;i++)
	  {
	  	f=f*i;
	  }
	  
	  return f;
}
Factorial of a given number

Output:

Command Prompt

Eneter a number:
5
Factorial of 5 is 120

Example HTML page

Leave a Reply

Your email address will not be published. Required fields are marked *

Pin It on Pinterest