Complementary task for topic: 2

M Nemeth · 2023-08-29 15:21:04.609219'

Loops: do/while: factorial

Loops: do/while: factorial

Task: Calculate the factorial of a positive integer:
Write a C program that prompts the user to enter a positive integer and calculates its factorial using a do-while loop. Display the result using printf().

Hint: In this task we can use the do/while loop to make our code more compact. Try to use the do while to read the number and handle if it is not a positive integer

Solution
#include 

int main() {
    int number;
    int factorial = 1;
    
    do {
        printf("Enter a positive integer: ");
        scanf("%d", &number);
        
        if (number < 0) {
            printf("Invalid input. Please enter a positive integer.\n");
        }
    } while (number < 0);
    
    int i = 1;
    while (i <= number) {
        factorial *= i;
        i++;
    }
    
    printf("The factorial of %d is %d.\n", number, factorial);
    
    return 0;
}



Explanation
In this example, the program uses a do-while loop to repeatedly prompt the user to enter a positive integer until a valid input is provided. Inside the loop, it uses printf() to prompt the user to enter a positive integer and scanf() to read the input and store it in the number variable.

If the number entered by the user is less than 0, it displays an error message using printf() and the loop continues.

Once a valid positive integer is entered, the program initializes the factorial variable to 1 and uses a while loop to calculate the factorial. The loop continues as long as i is less than or equal to number. Inside the loop, it updates the factorial by multiplying it with i, and increments i by 1.
< < previous    next > >