How to Write a C Program That Calculates the Average of Numbers Until 99 is Entered

How to Write a C Program That Calculates the Average of Numbers Until 99 is Entered

In this article, we will explore how to create a simple C program that reads numbers from the user and calculates their average until the user enters 99. This guide includes step-by-step instructions and example code to help you understand the process thoroughly.

Steps to Implement the Program

Initialize variables to store the sum of the numbers and the count of the numbers. Use a loop to read numbers from the user until 99 is entered. Add the number to the sum and increment the count if the number is not 99. Calculate the average of the entered numbers and print it after exiting the loop. Check if any numbers were entered before calculating the average.

Example Code

Code Snippet

#include iostream
using namespace std;
int main() {
    int number;
    double sum  0.0;
    int count  0;
    cout  "Enter numbers (enter 99 to stop):"  endl;
    // Loop until the user enters 99
    while (true) {
        cin  number;
        if (number  99) {
            break; // Exit the loop if the user enters 99
        }
        // Add the number to the sum and increment the count
        sum   number;
        count  ;
    }
    // Check if any numbers were entered
    if (count  0) {
        double average  sum / count; // Calculate the average
        cout  "The average is: "  average  endl;
    } else {
        cout  "No numbers were entered."  endl;
    }
    return 0;
}

Explanation

Input Loop

The while (true) loop continues to prompt the user for input until 99 is entered. This ensures that the program runs continuously until the user decides to stop.

Sum and Count

The program maintains a running total of the entered numbers (sum) and a count of how many valid numbers have been entered (count).

Average Calculation

After exiting the loop, the program calculates the average if at least one number has been entered. If no numbers were entered, it informs the user.

How to Compile and Run

Save the code in a file named average.cpp. Open your terminal/command prompt. Navigate to the directory where the file is saved. Compile the program using:
g   average.cpp -o average
Run the compiled program:
./average
Now you can enter numbers, and the program will calculate the average when you enter 99.

This simple program is a great example of how to work with user input and perform basic data processing in C. It demonstrates the use of loops and conditional statements to achieve a specific task.