factorial of a number in C

05 min read

C program to find the factorial of a number is given below. Factorial of a number n is the product of all number in decreasing order starting from the number n to 1. Factorial doesn't exist for a negative number.

factorial of n (n!) = n*........3*2*1

 


include
<stdio.h> int main() { int n, i; unsigned long long factorial = 1; printf("Enter an integer: "); scanf("%d",&n); if (n < 0) printf("Factorial of a negative number doesn't exist. Please enter a valid number"); else {
for(i=1; i<=n; ++i) {
factorial *= i; // factorial = factorial*i; } printf("Factorial of %d = %llu", n, factorial); } return 0;
}


 


output:

Enter an integer: 5 Factorial of 5=120


 

Factorial of a number using recursion

#include <stdio.h>
long int multiplyNumbers(int n);

int main()
{
    int n;
    printf("Enter a positive integer: ");
    scanf("%d", &n);
    printf("Factorial of %d = %ld", n, multiplyNumbers(n));
    return 0;
}
long int multiplyNumbers(int n)
{
    if (n >= 1)
        return n*multiplyNumbers(n-1);
    else
        return 1;
}

 

output:

Enter an integer: 4 Factorial of 4=24
POST A NEW COMMENT
     
  • Input (stdin)

    Output (stdout)


    Input (stdin)

    Your Output (stdout)

    Expected Output

    Compiler Message

    Input (stdin)

    2    3

    Your Output (stdout)

    5

    Expected Output

    5

    Compiler Message

    5

    Error