gpt-3.5-turbo-0613· OpenAI
WildChat-4.8M (AI2)
factorial of a number in c
- User
factorial of a number in c
- Assistant
To calculate the factorial of a number in C, you can use a loop to multiply all numbers from 1 to the given number.
Here's a sample code:
#include <stdio.h> int factorial(int num) { int fact = 1; for (int i = 1; i <= num; i++) { fact *= i; } return fact; } int main() { int number; printf("Enter a number: "); scanf("%d", &number); int result = factorial(number); printf("Factorial of %d is %d\n", number, result); return 0; }This code defines a function
factorial()that takes an integer as an argument and returns its factorial. It uses a for loop to calculate the factorial by multiplying each number from 1 to the given number. In themain()function, the user is asked to enter a number, and then the factorial is printed using theprintf()function.