Pages

Monday

Program to Find the Factorial of a Number in C | C Program

Here's a C program to find the factorial of a given number using For loop with output and proper explanation.

What is Factorial? The factorial of a non-negative integer n, denoted by n!, is the product of all positive integers less than or equal to n. The factorial of 0 and 1 is 1.

# include <stdio.h>
# include <conio.h>
void main() 
{ 
 long n, i, f = 1 ; 
 clrscr() ; 
 printf("Enter a number : ") ; 
 scanf("%ld", &n) ; 
 for(i = 2 ; i <= n ; i++) 
  f = f * i ; 
 printf("\nFactorial value of %ld is : %ld", n, f) ; 
 getch() ; 
} 


Output of above program is

Enter a number : 5
Factorial value of 5 is : 120


Explanation of above program

There are three variables in this program all of type long - 
  • n - is the number whose factorial we're calculating.
  • f - is the factorial of n. It is initialized to 1 at the start of the program.
  • i - is the loop variable.

First we ask the user to enter a number. Then we calculate the factorial of that number using a for loop. Our for loop runs for the value of loop variable i = 2 to n. Inside the for loop we simply multiply each value of loop variable with previously calculated factorial value (f) and again storing it in the same f variable for further calculations.

Suppose, n = 5. So our for loop will run for the value of i = 2, 3, 4 and 5 -
  • i = 2, f = 1 - This is the first iteration. Inside the loop the value of f is updated as - f = f * i. So f = 1 * 2 = 2.
  • i = 3, f = 2 - The new value of f = f * i = 2 * 3 = 6.
  • i = 4, f = 6 - The new value of f = f * i = 6 * 4 = 24.
  • i = 5, f = 24 - The new value of f = f * i = 24 * 5 = 120.

Tip: We could have run our for loop from i = 1 to n but by doing this we're just wasting one looping cycle and hence the resources because in the first iteration if the value of i = 1 and f = 1 then again f = 1 * 1 = 1. As there is no change in the value of f we can eliminate this step. Hence we're using our loop from i = 2 to n.

2 comments:

  1. . We introduce a sequence of integers 0 - end of the sequence. Whether a sequence contains at least three negative numbers. Calculate the sum of odd numbers and the product of prime numbers

    ReplyDelete
  2. awsome explanation! hanx dude

    ReplyDelete