Factorial Example Using Function


Explanation

A user-defined function can receive a number as a parameter and perform a specific task. In this program, the factorial() function accepts a number, calculates its factorial using a for loop, and displays the result. The same function is called with different values to calculate multiple factorials.

How It Works?

  • Step 1: Include the required header files stdio.h and conio.h.
  • Step 2: Create a user-defined function factorial(int no) that accepts a number.
  • Step 3: Declare the variables k and f, and initialize f = 1.
  • Step 4: Use a for loop from 1 to no.
  • Step 5: Multiply f by k during each iteration to calculate the factorial.
  • Step 6: Display the factorial using the printf() function.
  • Step 7: Call the factorial() function with different numbers from the main() function.

Example Program


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

void factorial(int no)
{

    int k, f;

    f = 1;

    for(k = 1; k <= no; k++)
    {

        f = f * k;

    }

    printf("\n Factorial of %d is %d", no, f);

}

int main()
{

    clrscr();

    factorial(3);

    factorial(4);

    getch();

}

Output

Factorial of 3 is 6
Factorial of 4 is 24

Practice Exercises

Task 1: Write a C program using a function named factorial() to calculate the factorial of a given number. Call the function for the numbers 5 and 6 and display their factorials.

Goal: Learn how to pass arguments to a user-defined function and calculate the factorial of different numbers using the same function.

💡 Hint: Create a function factorial(int no). Initialize f = 1, use a for loop from 1 to no, multiply f by k in each iteration, and call the function twice from main().
💡 Show Solution

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

void factorial(int no)
{

    int k, f;

    f = 1;

    for(k = 1; k <= no; k++)
    {

        f = f * k;

    }

    printf("\n Factorial of %d is %d", no, f);

}

int main()
{

    clrscr();

    factorial(5);

    factorial(6);

    getch();

}

Output
Factorial of 5 is 120
Factorial of 6 is 720
Explanation: The program defines a user-defined function factorial() that accepts a number as a parameter. Inside the function, a for loop calculates the factorial by multiplying all numbers from 1 to the given number. The function is called twice from the main() function to calculate the factorials of 5 and 6, demonstrating function reusability.