Course Content
Detailed Content of Programming in C
0/1
Introduction
0/1
Structure of C program
0/1
Answers of ‘C’ Pointers Programs
0/1
About Lesson

Create a program that calculates the factorial of a given number. Use a loop to perform the calculation and display the result.

#include <stdio.h>

int main() {
// Declare variables
int number;
long long factorial = 1;

// Input: Get the number from the user
printf(“Enter a positive integer: “);
scanf(“%d”, &number);

// Check if the number is negative
if (number < 0) {
printf(“Error: Factorial is not defined for negative numbers.n”);
return 1; // Exit the program with an error code
}

// Process: Calculate the factorial using a loop
for (int i = 1; i <= number; i++) {
factorial *= i;
}

// Output: Display the result
printf(“Factorial of %d = %lldn”, number, factorial);

return 0; // Exit the program successfully
}