Complementary task for topic: 2

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

Loops: While: Scan and termination IV.

Loops: While: Scan and termination IV.

Task: Find the average of a series of numbers:
Write a C program that continuously prompts the user to enter a number until they enter a negative number. The program should compute and display the average of all the numbers entered using a while loop and scanf().

Hint: In the loop condition we can check if the termination happened or not.
For the average you need to count the elements and calculate the sum.

Solution
#include 

int main() {
    int number;
    int sum = 0;
    int count = 0;
    
    printf("Enter a number (-1 to stop): ");
    scanf("%d", &number);
    
    while (number >= 0) {
        sum += number;
        count++;
        
        printf("Enter a number (-1 to stop): ");
        scanf("%d", &number);
    }
    
    if (count == 0) {
        printf("No numbers entered.\n");
    } else {
        double average = (double)sum / count;
        printf("The average of the numbers entered is %.2f.\n", average);
    }
    
    return 0;
}



Explanation
In this example, the program initializes the number variable to store the user input, the sum variable to keep track of the sum, and the count variable to keep track of the number of inputs. 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 greater than or equal to 0. Inside the loop, it adds the current number to the sum and increments the count. After each iteration, it prompts the user to enter another number using printf() and scanf() to repeat the process. Once the user enters a negative number, the loop terminates. If no numbers were entered (i.e., count is 0), it displays a message stating that no numbers were entered. Otherwise, it calculates the average by dividing the sum by the count (casting sum to a double to ensure floating-point division) and uses printf() to display the average.
< < previous    next > >