Calculate Factorial of a Given Number in C

 

 

Factorial Calculation in C

This program calculates the factorial of a given number using the C programming language. The factorial of a non-negative integer n is the product of all positive integers less than or equal to n. It is denoted by n!.

Program Explanation

The program uses a simple iterative approach to calculate the factorial. It multiplies all the integers from 1 up to the given number n to get the factorial value.

C Program


            #include <stdio.h>

            /**
             * Function to calculate the factorial of a given number.
             *
             * @param n The number for which the factorial is to be calculated.
             * @return The factorial of the given number.
             */
            long long factorial(int n) {
                long long fact = 1;
                for (int i = 1; i <= n; ++i) {
                    fact *= i;
                }
                return fact;
            }

            /**
             * Main function to drive the program.
             */
            int main() {
                int number;

                // Asking the user for input
                printf("Enter a positive integer: ");
                scanf("%d", &number);

                // Checking for non-negative input
                if (number < 0) {
                    printf("Factorial is not defined for negative numbers.\n");
                } else {
                    // Calculating factorial and displaying the result
                    printf("Factorial of %d = %lld\n", number, factorial(number));
                }

                return 0;
            }
        

Explanation of the Program

The program consists of the following components:

  • factorial function: This function takes an integer n as input and returns the factorial of n. It initializes a variable fact to 1 and iteratively multiplies it by each integer from 1 to n.
  • main function: This is the entry point of the program. It prompts the user to enter a positive integer and checks if the input is non-negative. If the input is valid, it calls the factorial function and prints the result. If the input is negative, it displays an appropriate message.

This program provides a simple and clear way to understand the concept of calculating factorials in C, with adequate input validation to ensure correct results.

 

Leave a Reply

Your email address will not be published. Required fields are marked *