Skip to content

← Back to Overview

Sum and Average of Three Numbers

Concept Explanation

What is it?

This concept involves taking three numerical inputs, computing their sum, and then determining their average. The sum is the total value obtained by adding all numbers together, while the average (or mean) is the sum divided by the count of the numbers.

Why is it important?

Calculating sums and averages is a fundamental operation in many fields, including statistics, data analysis, and everyday calculations. It helps summarize data, understand central tendencies, and forms the basis for more complex statistical analyses.

Where is it used?

  • Financial Applications: Calculating average monthly expenses, profits, or stock prices.
  • Scientific Research: Finding average readings from experiments.
  • Education: Calculating average grades.
  • Data Analysis: Summarizing datasets.

Real-world example

If you want to know your average score across three tests, you add up the scores and divide by three. Similarly, if a company wants to find the average sales per month over a quarter, they sum up the sales for three months and divide by three.


Algorithm

  1. Start.
  2. Get three numbers (num1, num2, num3) from the user.
  3. Calculate the sum: sum = num1 + num2 + num3.
  4. Calculate the average: average = sum / 3.
  5. Display the calculated sum and average.
  6. End.

Edge Cases: - Non-numeric input (handled by language-specific error mechanisms or explicit validation). - Division by zero is not an issue here as we divide by a fixed number (3).


Implementations

import java.util.Scanner;

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

        System.out.print("Enter the first number: ");
        double num1 = scanner.nextDouble();

        System.out.print("Enter the second number: ");
        double num2 = scanner.nextDouble();

        System.out.print("Enter the third number: ");
        double num3 = scanner.nextDouble();

        // Calculate sum
        double sum = num1 + num2 + num3;

        // Calculate average
        double average = sum / 3;

        System.out.println("Numbers: " + num1 + ", " + num2 + ", " + num3);
        System.out.println("Sum: " + sum);
        System.out.println("Average: " + String.format("%.2f", average));

        scanner.close();
    }
}
# Get three numbers from the user
num1_str = input("Enter the first number: ")
num1 = float(num1_str)

num2_str = input("Enter the second number: ")
num2 = float(num2_str)

num3_str = input("Enter the third number: ")
num3 = float(num3_str)

# Calculate sum
sum_numbers = num1 + num2 + num3

# Calculate average
average = sum_numbers / 3

print(f"Numbers: {num1}, {num2}, {num3}")
print(f"Sum: {sum_numbers}")
print(f"Average: {average:.2f}") # Format to 2 decimal places
#include <stdio.h>

int main() {
    double num1, num2, num3;
    double sum, average;

    printf("Enter the first number: ");
    scanf("%lf", &num1);

    printf("Enter the second number: ");
    scanf("%lf", &num2);

    printf("Enter the third number: ");
    scanf("%lf", &num3);

    // Calculate sum
    sum = num1 + num2 + num3;

    // Calculate average
    average = sum / 3;

    printf("Numbers: %.2lf, %.2lf, %.2lf, num1, num2, num3);
    printf("Sum: %.2lf, sum);
    printf("Average: %.2lf", average);

    return 0;
}
SET SERVEROUTPUT ON;
DECLARE
  num1        NUMBER := &Enter_First_Number;
  num2        NUMBER := &Enter_Second_Number;
  num3        NUMBER := &Enter_Third_Number;
  sum_val     NUMBER;
  average_val NUMBER;
BEGIN
  DBMS_OUTPUT.PUT_LINE('--- Sum and Average of Three Numbers ---');

  DBMS_OUTPUT.PUT_LINE('Enter the first number: ');
  -- To use substitution variables more interactively in a script:
  -- num1 := '&num1_input'; would be typically how you'd get input before running.
  -- For this demonstration, we are pre-assigning values or expecting input via the '&' prompt.

  sum_val := num1 + num2 + num3;
  average_val := sum_val / 3;

  DBMS_OUTPUT.PUT_LINE('Numbers: ' || num1 || ', ' || num2 || ', ' || num3);
  DBMS_OUTPUT.PUT_LINE('Sum: ' || sum_val);
  DBMS_OUTPUT.PUT_LINE('Average: ' || ROUND(average_val, 2));
END;
/

Explanation

  • Java: Uses Scanner to get three double inputs. Performs addition and division. String.format("%.2f", average) is used for formatted output of the average.
  • Python: Uses input() to get three string inputs, which are then converted to float. f-strings are used for formatted output.
  • C: Employs scanf("%lf", ...) to read three double inputs and printf("%.2lf, ...) for formatted output.
  • Oracle: Implemented in PL/SQL. Uses substitution variables (&Enter_First_Number, etc.) for user input (which get prompted at runtime in SQL*Plus/SQL Developer). Calculates sum and average, and displays with DBMS_OUTPUT.PUT_LINE and ROUND for formatting.

Complexity Analysis

  • Time Complexity: O(1) - The number of operations is constant, regardless of the input values.
  • Space Complexity: O(1) - A fixed number of variables are used.

Flowchart

graph TD
    A[Start] --> B[Get num1]
    B --> C[Get num2]
    C --> D[Get num3]
    D --> E[Calculate Sum = num1 + num2 + num3]
    E --> F[Calculate Average = Sum / 3]
    F --> G[Display Sum and Average]
    G --> H[End]

Sample Dry Run

Step num1 num2 num3 Sum Average Description
Input 10 20 30 - - User enters three numbers
Process 10 20 30 60 - Sum = 10 + 20 + 30
Process 10 20 30 60 20 Average = 60 / 3
Output - - - 60 20 Display Sum (60) and Average (20)

Practice Problems

Easy

  • Modify the program to calculate the sum and average of four numbers.
  • Take numbers as input until the user enters 0, then calculate their sum and average.

Medium

  • Implement a function/method to calculate the average of an array/list of numbers.
  • Add input validation to ensure only numbers are entered.

Hard

  • Calculate the weighted average of numbers, where each number has a specific weight.
  • Calculate standard deviation along with the average.

"The difference between a successful person and others is not a lack of strength, not a lack of knowledge, but rather a lack of will." - Vince Lombardi