Complementary task for topic: 2

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

Loops: While: Scan and termination III.

Loops: While: Scan and termination III.

Task: Count the number of positive integers entered by the user:
Write a C program that continuously prompts the user to enter a number until they enter 0. The program should count and display the number of positive integers entered using a while loop and scanf().

Hint: in the loop condition we can check if the termination happened or not.

Solution
#include 

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



Explanation
In this example, the program initializes the number variable to store the user input and the count variable to keep track of the number of positive integers. It uses printf() to prompt the user to enter a number and scanf() to scan the input and store it in the number variable. The program then enters a while loop that continues as long as the number entered by the user is not 0. Inside the loop, it checks if the current number is positive. If it is, it increments the count variable. After each iteration, it prompts the user to enter another number using printf() and scanf() to repeat the process. Once the user enters 0, the loop terminates, and it uses printf() to display the count of positive integers.
< < previous    next > >