Complementary task for topic: 10

M Nemeth · 2023-08-29 15:21:04.632218'

Recursion: factorial

Recursion: factorial

Create a C program to calculate factorial with recursion!

Hint: We call recursive function when the function calles itself. Weat we need is to think over, when we want to finish the process. E.g. we know that n!=n*(n-1)!, but that cannot go forever, so we have to define a base:0!=1 and 1!=1.

Solution
#include 

// Function to calculate the factorial using recursion
unsigned long long factorial(int n) {
    if (n == 0 || n == 1) {
        return 1;
    } else {
        return n * factorial(n - 1);
    }
}

int main() {
    int num;
    printf("Enter a positive integer: ");
    scanf("%d", &num);

    if (num < 0) {
        printf("Error: Factorial is not defined for negative numbers.\n");
    } else {
        unsigned long long result = factorial(num);
        printf("Factorial of %d is: %llu\n", num, result);
    }

    return 0;
}



Explanation
The main function prompts the user to enter a positive integer.
The user inputs the number, and the program reads it using scanf.
The main function then calls the factorial function, passing the entered number as an argument.
The factorial function uses recursion to calculate the factorial. It checks if the input n is either 0 or 1; if so, it returns 1 (since 0! and 1! both equal 1). Otherwise, it calculates n * factorial(n - 1)
Note: Recursion is not always the most efficient way to solve a problem, and there are often iterative alternatives that may be more performant. However, using recursion for certain problems can provide a clearer and more concise way to express the solution.
< < previous    next > >