[Programming] Question 6: Calculate the factorial of a number in C?

Learn how to write a C program to calculate the factorial of a number. This guide explains how to implement iterative methods for computing the factorial, including detailed examples and explanations. Ideal for beginners who want to understand fundamental concepts in C programming and factorial computation.

#include <stdio.h>

int main() {
	int n, i;
	unsigned long long factorial = 1;

	printf("Enter a positive integer: ");
	scanf("%d", &n);

	for (i = 1; i <= n; ++i) {
		factorial *= i;
	}

	printf("Factorial of %d = %llu\n", n, factorial);

	return 0;
} 
Explanation: 

Inside the main() function:

- An integer variable n is declared to store the input number.

- An unsigned long long variable factorial is initialized to 1 to store the factorial value.

- The user is prompted to enter a positive integer.

- A for loop is used to iterate from 1 to the entered number.

- Within the loop, each number is multiplied to the factorial variable.

- Finally, the factorial of the entered number is printed to the console.

 

 

Featured Posts

Leetcode 4. Median of Two Sorted Arrays

  4. Median of Two Sorted Arrays Hard Given two sorted arrays  nums1  and  nums2  of size  m  and  n  respectively, return  the median  of t...

Popular Posts