Search

C Tutorial

.

• Abhinav Rai Created by
• Views
• 4 (429 ratings)
• 02/03/2024 Last Updated

C Tutorial

# C Program for Factorial

A non-negative integer n’s factorial, symbolised by n! in mathematics, is the result of all positive integers below or equal to n. For example, the factorial of 5 is calculated as 5! = 5 x 4 x 3 x 2 x 1 = 120.

Calculating the factorial of a number is a common programming problem. In this article, we will explore various methods to implement the factorial program in the C programming language.

## Algorithm of Factorial Program in C

The algorithm for calculating the factorial of a number can be defined as follows:

1. Initialise a variable result to 1.

2. Iterate from 1 to the given number n.

3. Multiply the result by the current number in each iteration.

4. After the loop ends, the result will contain the factorial of the given number.

Now, let's dive into different implementations of the factorial program in C.

## C Program to Find Factorial Using For Loop

In this method, we will calculate the factorial program in C using for loop. The for loop will iterate from 1 to the given number and multiply the result with the current number in each iteration.

 #include unsigned long long factorial(unsigned int n){    unsigned long long result = 1;    for (unsigned int i = 1; i <= n; ++i)    {        result *= i;    }    return result;}int main(){    unsigned int number;    printf("Enter a non-negative integer: ");    scanf("%u", &number);    printf("Factorial of %u = %llu\n", number, factorial(number));    return 0;}

In the above code, we have defined a function factorial() that takes an unsigned integer n as input and returns the factorial of n. The main function prompts the user to enter a non-negative integer, calls the factorial() function, and displays the result.

## C Program to Find Factorial Using While Loop

Another way to find the factorial of a number is by using a factorial program in C while loop. The while loop will iterate until the number becomes zero and multiply the result with the current number in each iteration.

 #include unsigned long long factorial(unsigned int n){    unsigned long long result = 1;    while (n > 1)    {        result *= n;        n--;    }    return result;}int main(){    unsigned int number;    printf("Enter a non-negative integer: ");    scanf("%u", &number);    printf("Factorial of %u = %llu\n", number, factorial(number));    return 0;}

In this code, the factorial() function uses a while loop to calculate the factorial. The loop continues until the value of n becomes 1, and in each iteration, it multiplies the result with n and decrements n by 1.

## C Program to Find Factorial Using Recursion

Recursion is a technique where a function calls itself. We can implement the factorial in C using recursion by defining a recursive function that calls itself with a smaller input value.

 #include unsigned long long factorial(unsigned int n){    if (n == 0)        return 1;    else        return n * factorial(n - 1);}int main(){    unsigned int number;    printf("Enter a non-negative integer: ");    scanf("%u", &number);    printf("Factorial of %u = %llu\n", number, factorial(number));    return 0;}

In the above code, the factorial() function is defined recursively. If the input n is 0, it returns 1 (base case). Otherwise, it multiplies n with the factorial of n - 1, which is obtained by recursively calling the factorial() function.

## C Program for Factorial Using Ternary Operator

The ternary operator ?: can be used to implement the factorial program concisely. The ternary operator evaluates a condition and returns one of two values based on the result.

 #include unsigned long long factorial(unsigned int n){    return (n == 0) ? 1 : n * factorial(n - 1);}int main(){    unsigned int number;    printf("Enter a non-negative integer: ");    scanf("%u", &number);    printf("Factorial of %u = %llu\n", number, factorial(number));    return 0;}

In this code, the factorial() function uses the ternary operator to check if n is 0. If it is, the function returns 1; otherwise, it multiplies n with the factorial of n - 1 obtained by calling the factorial() function recursively.

## C Program to Find Factorial Using tgamma() Method

The tgamma() function is a built-in function in C that calculates the gamma function of a given argument. The gamma function is a generalisation of the factorial function for real and complex numbers. By utilising the tgamma() method, we can indirectly find the factorial of a number in a concise and efficient manner.

In this code, we utilize the tgamma() function from the math.h library to indirectly calculate the factorial of a non-negative integer. The tgamma() function calculates the gamma function for the argument n + 1. Since the gamma function is a generalization of the factorial function, evaluating tgamma(n + 1) for a non-negative integer n gives us the factorial value.

 #include #include unsigned long long factorial(unsigned int n){    return tgamma(n + 1);}int main(){    unsigned int number;    printf("Enter a non-negative integer: ");    scanf("%u", &number);    printf("Factorial of %u = %llu\n", number, factorial(number));    return 0;}

In the above code, the factorial() function utilises the tgamma() function from the <math.h> header. The tgamma(n + 1) expression calculates the gamma function of n + 1, which is equivalent to the factorial of n.

## C Program to Find Factorial Using Function

In this implementation, we define a separate function to find factorial in c using function. The main function prompts the user to enter a non-negative integer, calls the factorial function, and displays the result.

 #include unsigned long long factorial(unsigned int n);int main(){    unsigned int number;    printf("Enter a non-negative integer: ");    scanf("%u", &number);    printf("Factorial of %u = %llu\n", number, factorial(number));    return 0;}unsigned long long factorial(unsigned int n){    unsigned long long result = 1;    for (unsigned int i = 1; i <= n; ++i)    {        result *= i;    }    return result;}

In this code, the factorial() function is defined separately above the main() function. It follows the implementation using a for loop, as explained earlier.

## C Program to Find Factorial Using Pointers

Pointers can be used to find the factorial of a number by passing the address of the result variable to the function.

 #include void factorial(unsigned int n, unsigned long long *result);int main(){    unsigned int number;    unsigned long long result;    printf("Enter a non-negative integer: ");    scanf("%u", &number);    factorial(number, &result);    printf("Factorial of %u = %llu\n", number, result);    return 0;}void factorial(unsigned int n, unsigned long long *result){    *result = 1;    for (unsigned int i = 1; i <= n; ++i)    {        *result *= i;    }}

In this code, the factorial() function takes two arguments: the number n and a pointer to the result variable. Inside the function, we use the *result notation to access the value stored at the memory address pointed to by result.

## C Program to Find Factorial Series

Here’s how you can construct a C program to find factorial series:

 #include // Function to calculate the factoriallong long factorial(int n) {    long long fact = 1;    for(int i = 2; i <= n; i++) {        fact *= i;    }    return fact;}int main() {    int num;       printf("Enter the number of terms in the series: ");    scanf("%d", &num);       printf("The factorial series up to %d is: \n", num);    for(int i = 0; i <= num; i++) {        printf("Factorial of %d = %lld\n", i, factorial(i));    }       return 0;}

Here’s how this program works:

1. The factorial function calculates the factorial of a number. It starts with the fact variable set to 1, then multiplies it by every integer from 2 up to n. This is because the factorial of a number is the product of all positive integers up to that number.

2. The main function first asks the user to enter the number of terms in the series. This input is stored in the num variable.

3. It then prints the factorial series up to num. For each integer i from 0 to num, it calls the factorial function to calculate the factorial of i and then prints the result.

Note: The factorial function returns a long long because factorials can become very large very quickly. For example, the factorial of 20 is already larger than what can be stored in a 32-bit int.

Also, keep in mind that this program doesn't handle potential overflow issues when calculating factorials of large numbers, as long long can hold values up to 9223372036854775807 in C language (as of the C99 standard). This means that factorials of numbers greater than 20 will overflow and produce incorrect results.

For a complete solution, you might consider using arbitrary precision arithmetic libraries (like GMP) or implementing a similar feature in your code.

## Conclusion

In this article, we explored various methods to calculate the factorial of a number in C. We discussed implementations using loops, recursion, and built-in functions. By understanding these different approaches, you can choose the method that best suits your needs and programming style.

Calculating factorials is a fundamental programming concept, and mastering it can enhance your problem-solving skills. Whether you prefer iterative solutions using loops or elegant recursive implementations, the choice is yours.

If you want to expand your C programming knowledge and explore more advanced topics, consider checking out the Executive PG Program in Software Development- Full Stack by upGrad. Their immersive learning approach can provide you with valuable insights and hands-on experience.

Happy learning and happy coding!

## FAQs

Q: How do I calculate the factorial of a number in C?
To calculate the factorial of a number in C, you can use various methods such as using loops, recursion, or built-in functions. Some common approaches include using a for loop, a while loop, or a recursive function. You can choose the method that best suits your needs and programming style.

Q: Can I calculate the factorial of a negative number in C?
No, the factorial is mathematically defined for non-negative integers only. In C, attempting to calculate the factorial of a negative number will not produce meaningful results. It's important to ensure that the input for factorial calculations is a non-negative integer.

Q: What is the maximum value for which I can calculate the factorial in C?
The maximum value for which you can accurately calculate the factorial in C depends on the data type you are using. For example, if you are using an unsigned int, the maximum factorial value you can calculate is limited by the maximum value that can be represented by the data type. If you exceed this limit, the result may overflow, leading to incorrect values.

Q: Which method is more efficient for calculating factorials in C: loops or recursion?
In general, iterative methods using loops, such as the for loop or the while loop, are often more efficient than recursive methods due to the overhead of function calls in recursion. However, for small input values, the difference in performance may not be significant. It's recommended to consider the simplicity and readability of the code along with performance when choosing a method.