Factorial Program in C | Factorial Program in C Using Recursion
1. Program for finding factorial of a number using for loop
This is the simplest way to find factorial of a program. In this program, we will ask the user to enter the number which user want to find factorial of that number.
The factorial of a negative number doesn’t exist so we will apply condition if the user enters a negative number.
Output:

Here the factorial of number may be large so we have used unsigned long long. If the user enters a negative number then the compiler will show an error message.

Logic:
1st Iteration: Here at first i=1,fact=1 and n=5 i.e(i<=n).fact=fact*i i.e fact=1*1=1.now i is incremented,so i becomes 2.
2nd Iteration: Here i=2,fact=1 and n=5 i.e(i<=n).fact=fact*i i.e fact=1*2=2.now i is incremented,so i becomes 3.
3rd Iteration: Here i=3,fact=2 and n=5 i.e(i<=n).fact=fact*i i.e fact=2*3=6.now i is incremented,so i becomes 4.
4th Iteration: Here i=4,fact=6 and n=5 i.e(i<=n).fact=fact*i i.e fact=6*4=24.now i is incremented,so i becomes 5.
5th Iteration: Here i=5,fact=24 and n=5 i.e(i<=n).fact=fact*i i.e fact=24*5=120.now i is incremented,so i becomes 5.
6th Iteration: now i is incremented to 6 which is greater than n 6>5 i.e(i>n) so the program is terminated and the answer is 120.
2. Factorial Program in C Using Recursion
Recursion:
It is the method in which the function calls itself directly or indirectly. Recursion consists of two main conditions i.e base condition and the recursive call.
Output:

In Above program int fact(int) is function prototype and in printf,fact(num) function call is made.
If the user enters 5 as the input then the call to the function fact(5) is made and 5 which is not equal to 0. So the flow goes to the else statement where return call is made to the fact(4).
This process continues till the 1 is returned and thus we get the factorial of 5 i.e 120.
3. Program to find factorial using While loop
It is the same program as a program of for loop.only difference is that we use while loop instead of while loop but the logic is the same.
Time Complexity of the above solution is O(n).
4. Program using do-while loop
In this program, we will ask user to enter the number which user want to find factorial of that number.
Output:

5. Program Using Pointers
Output:

In Pointer, we point address of Number to the address of Pointer variable. In the above program, we use P=&number where p is a pointer.
6. To find factorial using functions
This is the modular approach of the program. If we want to change in the code we need not change the whole code, instead, we will do change in function.
Output:

7. Using Call By Reference
In this program instead of user-declared value the address of variable will pass to the function we created.
Output:

Post a Comment