Find the factorial of a number |C Program|

Introduction

     Factorial calculation is a fundamental concept in mathematics and computer science. This C program calculates the factorial of a given number using an iterative approach. The blog post will discuss factorials, the iterative solution, and provide a detailed explanation of the code.  

Factorial

    The factorial of a non-negative integer n, denoted as n!, is the product of all positive integers less than or equal to n. For example, 5! = 5 x 4 x 3 x 2 x 1 = 120.

Code

    
     
    #include<stdio.h>
    #include<conio.h>

    void main() {
        int i, fact = 1, n;
        clrscr();
    
        // Input
        printf("Enter a number: ");
        scanf("%d", &n);
    
        // Factorial Calculation (Iterative Approach)
        if (n <= 0) {
            fact = 1;
        } else {
            for (i = 1; i <= n; i++) {
                fact = fact * i;
            }
        }
    
        // Output
        printf("Factorial of %d = %d\n", n, fact);
        getch();
    }
       
     


Output


    Enter a number: 5
    Factorial of 5 = 120
       


   
 In this example, the user inputs the number 5. The program then calculates and prints the factorial of 5, which is 120.
You can try running the program with different input numbers to observe how it accurately calculates the corresponding factorials. The output will display the factorial of the entered number using an iterative approach.


Explanation

1. Header Files:
    The program includes the standard input/output header <stdio.h> and the console input/output header     <conio.h>.
2. Main Function:
    The main function serves as the entry point of the program.
3. Input:
    Users input a number for which the factorial needs to be calculated.
4. Factorial Calculation (Iterative Approach):
    The program calculates the factorial using an iterative approach.
    It initializes fact to 1 and then multiplies it by each integer from 1 to n using a for loop.
5. Output:
    The program outputs the calculated factorial for the given input number.   

Conclusion

     This C program provides a practical example of calculating the factorial of a number using an iterative approach. Understanding the iterative solution to factorial calculation is essential for mastering loops in programming. Feel free to run the program with different input numbers to observe how it accurately calculates the corresponding factorials. This example serves as a valuable introduction to iterative solutions in C. Happy coding!

Post a Comment

0 Comments