Menu BAR

FEEL FREE TO ASK ANY PROGRAM and please mention any error if you find it

21 Jan 2024

C program that uses a loop to calculate the factorial of a given number

// Factorial program using function


#include <stdio.h>

// Function prototype

long long calculateFactorial(int n);

int main() {

    int number;
    // Get input from the user

    printf("Enter a non-negative integer: ");
    scanf("%d", &number);

    // Check if the input is non-negative

    if (number < 0) {
        printf("Please enter a non-negative integer.\n");
        return 1; // Return with an error code
   }

    // Calculate and display the factorial using a loop

    long long factorial = calculateFactorial(number);
    printf("Factorial of %d = %lld\n", number, factorial);
    return 0;

}

// Function to calculate factorial using a loop

long long calculateFactorial(int n) {
    if (n == 0 || n == 1) {
        return 1;
    } else {
         long long result = 1;
        for (int i = 2; i <= n; ++i) {
           result *= i;
        }
        return result;
    }
}


No comments:

Post a Comment