Thursday, April 2, 2020

C Program to Find Factorial of a Number

C Program Find Factorial of a Number  

  • The fractional of a positive number n is given.
The factorial of n (n!) = 1*2*3*4*5....n 
  • The factorial of a negative number doesn't exist.The factorial of 0 is 1.
#include 
int main()
{
    int n, i; // integer values
    unsigned long long fact = 1; // 32 bits ( 4 bytes)  
    printf("Enter an integer: "); // enter user 
    scanf("%d", &n); // storing value 

    // shows error if the user enters a negative integer
    if (n < 0)
        printf("Error! Factorial of a negative number doesn't exist.");
    else 
 {
        for (i = 1; i <= n; ++i)
      {
        
         fact *= i;
        
      }
        printf("Factorial of %d = %llu", n, fact);
    }

    return 0;
}

Output

Enter an integer = 10
Factorial of 10 is = 3628800

  • This program takes input from user positive number and computes the factorial using for loop. 
  • Since, the factorial of a number may be very large.the type of factorial variable is declared unsigned long long . 
  • If the user entered negative number, the program should display a custom error message.  
Happy coding

0 comments:

Post a Comment

Recent Posts