129,902 views
42 votes
42 votes
How to solve

write a function fact that takes an integer as a parameter and returns the factorial of that number in c program

User Akhil Prajapati
by
3.5k points

1 Answer

23 votes
23 votes

Answer:

#include <stdio.h>

// Function prototype

int fact(int num);

int main() {

int num = 5;

printf("The factorial of %d is %d\\", num, fact(num));

return 0;

}

// Function definition

int fact(int num) {

int result = 1;

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

result *= i;

}

return result;

}

Step-by-step explanation:

The fact() function takes an integer as a parameter and calculates the factorial of that number by using a for loop to multiply the numbers from 1 to the given number. It then returns the result of the calculation.

In this example, the main() function calls the fact() function and passes the value 5 as an argument. The fact() function calculates the factorial of 5 and returns the result, which is then printed to the console by the main() function.

User Nicolas D
by
2.9k points