Computer Science Of Engineering

Simple and practical computer science tutorials, programming guides, and engineering concepts for students and beginners.

Breaking

Friday, April 18, 2025

Find the factorial of given number using any loop in C

 Find the factorial of given number using any loop in C

Program:


#include <stdio.h>


int main() {

    int num, i;

    unsigned long long factorial = 1;  // Use unsigned long long to handle larger numbers

    

    // Prompt user for input

    printf("Enter a number: ");

    scanf("%d", &num);

    

    // Check if the number is negative

    if (num < 0) {

        printf("Factorial is not defined for negative numbers.\n");

    } else {

        // Calculate factorial using a for loop

        for (i = 1; i <= num; ++i) {

            factorial *= i;

        }

        

        // Output the result

        printf("Factorial of %d = %llu\n", num, factorial);

    }


    return 0;

}

Output:





No comments:

Post a Comment