Complementary task for topic: 2
M Nemeth · 2023-08-29 15:21:04.608221'
Loops: While: Factorial
Loops: While: Factorial
Compute the factorial of a positive integer using recursion:
Write a C program that prompts the user to enter a positive integer and computes its factorial using recursion and a while loop. Display the result using printf().
Hint: factorial. n!=1*2*3*...*n=n*(n-1)*(n-2)*....*1
Solution
#include
int computeFactorial(int number) {
int factorial = 1;
while (number > 1) {
factorial *= number;
number--;
}
return factorial;
}
int main() {
int number;
printf("Enter a positive integer: ");
scanf("%d", &number);
if (number < 0) {
printf("Invalid input. Please enter a positive integer.\n");
return 0;
}
int factorial = computeFactorial(number);
printf("The factorial of %d is %d.\n", number, factorial);
return 0;
}
Explanation
In this example, the program defines a function computeFactorial() that takes an integer argument number and computes its factorial using a while loop. Inside the function, the variable factorial is initialized to 1. The while loop continues as long as number is greater than 1. In each iteration, it multiplies the factorial by number and decrements number. Once number becomes 1, the loop terminates, and the factorial value is returned.