Day 21: Average Calculator

Objective

Your task today is to write a program that calculates the average of a list of numbers provided by the user. This is a fundamental mathematical operation, and implementing it will help you practice working with lists, loops, and arithmetic operations.

For example:

  • Input: Numbers: 10, 20, 30, 40
  • Output: Average: 25.0

Why This Challenge Is Important

Calculating averages is a common operation in various fields like:

  1. Data Analysis: Understanding trends in datasets.
  2. Gaming: Calculating player scores.
  3. Everyday Tasks: For example, finding the average cost of items.

This challenge will help you solidify concepts like:

  • Input parsing.
  • Summing values in a list.
  • Calculating and formatting the result.

Steps to Solve

1. Understand the Problem

  • The user will provide a list of numbers separated by spaces, commas, or another delimiter.
  • Your program will compute the sum of the numbers and divide it by the count of numbers to find the average.
  • Ensure the program handles both integers and floating-point numbers.

2. Plan Your Solution

  1. Prompt the user to enter a list of numbers.
  2. Parse the input into a list of numeric values.
  3. Calculate the sum of the numbers.
  4. Divide the sum by the count of numbers.
  5. Display the result to the user.

3. Optional Enhancements

  • Handle invalid inputs gracefully.
  • Allow the user to compute averages multiple times without restarting the program.

Code Examples

Python Example

Basic Average Calculation:

# Prompt the user for input
numbers = input("Enter a list of numbers separated by spaces: ").split()

# Convert input to a list of floats
numbers = [float(num) for num in numbers]

# Calculate the average
average = sum(numbers) / len(numbers)

# Display the result
print(f"The average is: {average:.2f}")

Handling Invalid Inputs:

# Function to calculate average
def calculate_average():
    try:
        # Prompt the user for input
        numbers = input("Enter a list of numbers separated by spaces: ").split()
        
        # Convert input to a list of floats
        numbers = [float(num) for num in numbers]
        
        # Calculate and display the average
        average = sum(numbers) / len(numbers)
        print(f"The average is: {average:.2f}")
    except ValueError:
        print("Invalid input. Please enter numeric values only.")
    except ZeroDivisionError:
        print("No numbers provided. Please enter at least one number.")

# Call the function
calculate_average()

Java Example

Basic Average Calculation:

import java.util.Scanner;

public class AverageCalculator {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        // Prompt the user for input
        System.out.print("Enter a list of numbers separated by spaces: ");
        String input = scanner.nextLine();

        // Split input and convert to array of numbers
        String[] inputNumbers = input.split(" ");
        double sum = 0;
        int count = inputNumbers.length;

        for (String number : inputNumbers) {
            sum += Double.parseDouble(number);
        }

        // Calculate and display the average
        double average = sum / count;
        System.out.printf("The average is: %.2f\n", average);
    }
}

Handling Invalid Inputs:

import java.util.Scanner;

public class AverageCalculator {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        try {
            // Prompt the user for input
            System.out.print("Enter a list of numbers separated by spaces: ");
            String input = scanner.nextLine();

            // Split input and convert to array of numbers
            String[] inputNumbers = input.split(" ");
            double sum = 0;
            int count = inputNumbers.length;

            for (String number : inputNumbers) {
                sum += Double.parseDouble(number);
            }

            // Calculate and display the average
            double average = sum / count;
            System.out.printf("The average is: %.2f\n", average);

        } catch (NumberFormatException e) {
            System.out.println("Invalid input. Please enter numeric values only.");
        } catch (ArithmeticException e) {
            System.out.println("No numbers provided. Please enter at least one number.");
        }
    }
}

JavaScript Example

Basic Average Calculation:

// Prompt the user for input
let input = prompt("Enter a list of numbers separated by spaces:");

// Convert input into an array of numbers
let numbers = input.split(" ").map(Number);

// Calculate the average
let sum = numbers.reduce((acc, num) => acc + num, 0);
let average = sum / numbers.length;

// Display the result
console.log(`The average is: ${average.toFixed(2)}`);

Handling Invalid Inputs:

// Prompt the user for input
let input = prompt("Enter a list of numbers separated by spaces:");

try {
    // Convert input into an array of numbers
    let numbers = input.split(" ").map(num => {
        if (isNaN(num)) {
            throw new Error("Invalid input");
        }
        return parseFloat(num);
    });

    // Calculate the average
    let sum = numbers.reduce((acc, num) => acc + num, 0);
    let average = sum / numbers.length;

    // Display the result
    console.log(`The average is: ${average.toFixed(2)}`);
} catch (error) {
    console.log("Error: Please enter valid numeric values.");
}

Edge Cases to Consider

  1. Empty Input: Handle cases where no numbers are entered.
  2. Invalid Input: Handle cases where non-numeric values are provided.
  3. Single Number: Ensure the program correctly handles a single input.
  4. Precision: Display the result with a specific number of decimal places (e.g., 2).

Extensions to Explore

  1. Weighted Average: Allow the user to input weights for each number.
  2. Statistics: Extend the program to calculate median, mode, and range.
  3. Large Datasets: Allow the program to handle larger inputs (e.g., files with numbers).

What You’ve Learned

  • How to calculate the average of a list of numbers.
  • How to handle and validate user input.
  • Practical use cases of list operations and arithmetic calculations.