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?
stdio.h and conio.h.factorial(int no) that accepts a number.k and f, and initialize f = 1.for loop from 1 to no.f by k during each iteration to calculate the factorial.printf() function.factorial() function with different numbers from the main() function.#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(); }
function named factorial() to calculate the factorial of a given number. Call the function for the numbers 5 and 6 and display their factorials.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().
#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(); }
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.