﻿ Calculate Factorial in C: User-Entered positive integer

# C Program: Calculate Factorial with while loop and User-entered positive integer

## C While Loop: Exercise-6 with Solution

Write a C program that prompts the user to enter a positive integer. It then calculates and prints the factorial of that number using a while loop.

Sample Solution:

C Code:

``````#include <stdio.h>

int main() {
int number;        // Variable to store the user input
long long factorial = 1;  // Variable to store the factorial, initialized to 1

// Prompt the user to enter a positive integer
printf("Input a positive integer: ");
scanf("%d", &number);  // Read the user input

// Check if the entered number is negative
if (number < 0) {
printf("Error: Input enter a non-negative integer.\n");
return 1;  // Exit the program with an error code
}

// Calculate the factorial using a while loop
while (number > 0) {
factorial *= number;  // Multiply the current factorial by the current number
number--;  // Decrement the number for the next iteration
}

// Print the calculated factorial
printf("Factorial: %lld\n", factorial);

return 0;  // Indicate successful program execution
}
```
```

Sample Output:

```Input a positive integer: 5
Factorial: 120
```
```Input a positive integer: -6
Error: Input enter a non-negative integer.
```

Explanation:

Here are key parts of the above code step by step:

• #include <stdio.h>: Include the standard input-output library for functions like "printf()" and "scanf()".
• int main() {: Start the main function.
• int number;: Declare an integer variable 'number' to store user input.
• long long factorial = 1;: Declare a long long variable 'factorial' and initialize it to 1 to store the factorial.
• printf("Enter a positive integer: ");: Prompt the user to enter a positive integer.
• scanf("%d", &number);: Read the user input and store it in the variable 'number'.
• if (number < 0) {: Check if the entered number is negative.
• printf("Error: Please input a non-negative integer.\n");: Print an error message if the number is negative.
• return 1;: Exit the program with an error code.
• while (number > 0) {: Start a while loop that continues as long as the 'number' is greater than 0.
• factorial *= number;: Multiply the current 'factorial' by the current 'number'.
• number--;: Decrement the 'number' for the next iteration.
• }: Close the while loop.
• printf("Factorial: %lld\n", factorial);: Print the calculated factorial using the %lld format specifier for long long.
• return 0;: Indicate successful program execution.
• }: Close the main function.

Flowchart:

C Programming Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.

﻿