The "Factorial Using Recursion" program in C calculates the factorial of a given non-negative integer using a recursive function. Recursion is a programming technique where a function calls itself to solve smaller instances of the same problem. The factorial of a number (denoted as ) is the product of all positive integers up to and is defined as follows:
- for
- (the base case)
Implementation of Factorial Using Recursion
Here’s a simple implementation of the factorial program using recursion in C:
Explanation of the Program
Header Files:
#include <stdio.h>
: This header is included for standard input and output functions.
Function Declaration:
long long factorial(int n)
: This function takes an integern
and returns its factorial as a long long integer. The return type islong long
to accommodate larger results, especially for larger values ofn
.
Base Case:
- The base case for the recursive function checks if
n
is 0. If it is, the function returns 1, as .
- The base case for the recursive function checks if
Recursive Case:
- If
n
is greater than 0, the function calls itself with the argumentn - 1
and multiplies the result byn
. This continues until the base case is reached.
- If
Main Function:
- The program starts by prompting the user to enter a non-negative integer.
- It uses
scanf()
to read the input value.
Negative Input Check:
- Before calculating the factorial, the program checks if the input number is negative. If it is, it informs the user that the factorial is not defined for negative numbers.
Calculating Factorial:
- If the input is valid (non-negative), the program calls the
factorial()
function and stores the result. - It then prints the factorial of the entered number.
- If the input is valid (non-negative), the program calls the
How to Run the Program
Compile the Code: Use a C compiler like
gcc
to compile the code.Execute the Program:
Input Data: Enter a non-negative integer when prompted.
Example Input/Output
Input:
Output:
Conclusion
The "Factorial Using Recursion" program in C demonstrates the power of recursion in simplifying complex problems. By breaking down the problem into smaller sub-problems, it provides a clear and elegant solution for calculating the factorial of a number. This program is a good example of how recursive functions can be implemented and used effectively in C programming.