Write a C program that calculates the factorial of a given non-negative integer.

Problem Statement:

Write a C program that calculates the factorial of a given non-negative integer.

Requirements:

  • The program should prompt the user to enter a non-negative integer.
  • It should calculate and display the factorial of the entered integer.
  • The factorial of a non-negative integer n, denoted as n!, is the product of all positive integers less than or equal to n.

Example:

    Enter a non-negative integer: 5
Factorial of 5 is: 120 

Constraints:

  • The input integer should be non-negative.
  • Handle cases where the input is zero or one separately (0! and 1! are both 1).
  • The factorial of large numbers may exceed the range of standard integer types. Handle such cases appropriately.
Program

   #include 

// Function to calculate factorial
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 non-negative integer: ");
    scanf("%d", &num);

    if (num < 0) {
        printf("Error: Please enter a non-negative integer.\n");
    } else {
        unsigned long long fact = factorial(num);
        printf("Factorial of %d is: %llu\n", num, fact);
    }

    return 0;
}
 
The provided C program calculates the factorial of a non-negative integer entered by the user. It begins by prompting the user to input a non-negative integer. If the input is valid (non-negative), it calculates and displays the factorial of the entered number. 

The `factorial` function is implemented recursively to compute the factorial of an integer. If the input is 0 or 1, the factorial is defined as 1. For other non-negative integers, the factorial is calculated by multiplying the integer with the factorial of its predecessor. 

The program appropriately handles cases where the input integer is negative or zero, displaying an error message in such scenarios.

0 Comments

Post a Comment

Post a Comment (0)

Previous Post Next Post