Basic program #2

2. Read any number and find factorial of a number. (Using Loop)

#include <stdio.h>
int main()
{
    int n, i;
    unsigned long long factorial = 1;

    printf("Enter an integer to find it's factorial: ");
    scanf("%d",&n);

    // show error if the user enters a negative integer
    if (n < 0)
        printf("Error! Factorial of a negative number doesn't exist.");

    else
    {
           i=1;
        while(i<=n)
        {
            factorial *= i;              // factorial = factorial*i;
            i++;
        }
        printf("Factorial of %d = %llu\n", n, factorial);
    }
}

Output

  • Enter an integer to find it's factorial: 5
    Factorial of 5 = 120 
  • Enter an integer to find it's factorial: 6
    Factorial of 6 = 720
  • Enter an integer to find it's factorial: 3
    Factorial of 3 = 6 



Note:

The factorial of a positive number n is given by:
factorial of n (n!) = 1*2*3*4....n 
 
The factorial of a negative number doesn't exist. 
And, the factorial of 0 is 1, 0! = 1 
 
This program takes a positive integer from the user and computes factorial using for loop.

Since the factorial of a number may be very large, the type of factorial variable is declared as unsigned long long.

If the user enters negative number, the program displays error message.

You can also find the factorial of a number using recursion.

For download this program please check the link ➡➡ Download

 

Comments

Popular

Basic Program #3

Pointer Program #1

Array Program #4

Singly Linked List program #1