C Program to Calculate Factorial of a Number

Introduction:

Calculating the factorial of a number is a classic programming task used to teach iteration and mathematical logic. In this article, you will learn how to write a C program to find factorial of a number using a for loop. This logic is often used in mathematics, statistics, and algorithm development.


Problem Statement:

Write a C program that:

  • Takes an integer input from the user.
  • Calculates and prints the factorial of the given number.

C Program Code:

#include <stdio.h>

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

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

// Check for valid input
if (num < 0) {
printf("Factorial of a negative number doesn't exist.\n");
} else {
// Calculate factorial
for (i = 1; i <= num; i++) {
factorial *= i;
}

// Display result
printf("Factorial of %d is %llu\n", num, factorial);
}

return 0;
}

Explanation of the Code:

  1. The program accepts an integer from the user.
  2. It checks whether the input is negative, as factorials are not defined for negative numbers.
  3. A for loop is used to multiply numbers from 1 to n to compute the factorial.
  4. The result is printed using printf.

Example Output:

Enter a positive integer: 5
Factorial of 5 is 120
Enter a positive integer: -3
Factorial of a negative number doesn't exist.

Conclusion:

This program is a great way to practice loops and mathematical operations in C. Understanding how to compute factorials is foundational for solving more advanced problems in combinatorics and algorithms.

To continue building your skills, check out our guide on C Program to Check Prime Number.

Previous Article

C Program to Check if Last Digit of a Number is Even or Odd

Next Article

C Program to Reverse a Number – Simple Logic with Code

Write a Comment

Leave a Comment

Your email address will not be published. Required fields are marked *

Subscribe to our Newsletter

Subscribe to our email newsletter to get the latest posts delivered right to your email.
Pure inspiration, zero spam ✨