GoogleTag

Google Search

[Programming] Question 20: Write a program to Factorial of a Number

Learn how to write a C program to compute the factorial of a given number. This guide covers iterative methods for calculating factorials, including clear explanations and sample code for this approach. Understand the concept of factorial and how to implement it efficiently in C.

#include <stdio.h>

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

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

	if (num < 0)
		printf("Error! Factorial of a negative number doesn't exist.");
	else {
		for (i = 1; i <= num; ++i) {
			factorial *= i;
		}
		printf("Factorial of %d = %llu\n", num, factorial);
	}

	return 0;
} 

Inside the main() function:

- An integer variable `num` 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.

- If the entered number is negative, it prints an error message.

- Otherwise, a for loop calculates the factorial of the number.

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



Featured Posts

SQL Interview Questions Topics

 SQL Topics to prepare for interviews,   SQL Basics: Introduction to SQL SQL Data Types DDL (Data Definition Language): C...

Popular Posts