Complementary task for topic: 2

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

Loops: do/while: termination

Loops: do/while: termination

Task: Calculate the sum of positive integers until a terminating number is entered:
Write a C program that continuously prompts the user to enter a positive integer and calculates the sum of all the positive integers entered until a terminating number (e.g., -1) is entered. Display the final sum using printf().

Hint: Same idea as with while, but we do not need to write the scanf() call twice.

Solution
#include 

int main() {
    int number;
    int sum = 0;
    
    do {
        printf("Enter a positive integer (-1 to stop): ");
        scanf("%d", &number);
        
        if (number > 0) {
            sum += number;
        }
    } while (number != -1);
    
    printf("The sum of the positive integers entered is %d.\n", sum);
    
    return 0;
}



Explanation
In this example, the program uses a do-while loop to repeatedly prompt the user to enter a positive integer until the terminating number (-1) is entered. 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 positive, it adds it to the sum variable. The loop continues until the terminating number (-1) is entered.
< < previous    next > >