Day 5: Simple Calculator

Objective

In today’s task, you will create a simple calculator program that performs basic arithmetic operations: addition, subtraction, multiplication, and division. This task will combine skills you’ve learned so far, such as taking user input, using variables, and employing conditional statements.

The goal is to allow the user to:

  1. Input two numbers.
  2. Choose an operation (add, subtract, multiply, or divide).
  3. Display the result of the chosen operation.

Helpful Tips to Solve the Task

1. Plan the Program Structure

Your program will follow these steps:

  1. Ask the user to input two numbers.
  2. Ask the user to select an operation (e.g., +, -, *, /).
  3. Perform the chosen operation.
  4. Display the result to the user.

2. Get User Input

Input Two Numbers:
Ensure the inputs are converted to numeric types (e.g., int or float). Use int() or float() in Python, nextInt() or nextDouble() in Java, and parseInt() or parseFloat() in JavaScript for this purpose.

Example in Python:

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

Input the Operation:
Ask the user which operation they’d like to perform.

Example in Python:

operation = input("Choose an operation (+, -, *, /): ")

3. Perform the Calculation

Use conditional statements to execute the operation based on the user’s choice.

  • For addition (+), return num1 + num2.
  • For subtraction (-), return num1 - num2.
  • For multiplication (*), return num1 * num2.
  • For division (/), return num1 / num2 (but check for division by zero).

Example in Python:

if operation == "+":
    result = num1 + num2
elif operation == "-":
    result = num1 - num2
elif operation == "*":
    result = num1 * num2
elif operation == "/":
    if num2 != 0:
        result = num1 / num2
    else:
        result = "Error! Division by zero is not allowed."
else:
    result = "Invalid operation selected."

4. Display the Result

After performing the operation, display the result to the user.

print(f"The result is: {result}")

5. Examples for Different Languages

Python Example:

num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))
operation = input("Choose an operation (+, -, *, /): ")

if operation == "+":
    result = num1 + num2
elif operation == "-":
    result = num1 - num2
elif operation == "*":
    result = num1 * num2
elif operation == "/":
    if num2 != 0:
        result = num1 / num2
    else:
        result = "Error! Division by zero is not allowed."
else:
    result = "Invalid operation selected."

print(f"The result is: {result}")

Java Example:

import java.util.Scanner;

public class Main {
    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("Choose an operation (+, -, *, /): ");
        String operation = scanner.next();

        double result;
        switch (operation) {
            case "+":
                result = num1 + num2;
                System.out.println("The result is: " + result);
                break;
            case "-":
                result = num1 - num2;
                System.out.println("The result is: " + result);
                break;
            case "*":
                result = num1 * num2;
                System.out.println("The result is: " + result);
                break;
            case "/":
                if (num2 != 0) {
                    result = num1 / num2;
                    System.out.println("The result is: " + result);
                } else {
                    System.out.println("Error! Division by zero is not allowed.");
                }
                break;
            default:
                System.out.println("Invalid operation selected.");
        }
    }
}

JavaScript Example:

let num1 = parseFloat(prompt("Enter the first number: "));
let num2 = parseFloat(prompt("Enter the second number: "));
let operation = prompt("Choose an operation (+, -, *, /): ");

let result;
if (operation === "+") {
    result = num1 + num2;
} else if (operation === "-") {
    result = num1 - num2;
} else if (operation === "*") {
    result = num1 * num2;
} else if (operation === "/") {
    if (num2 !== 0) {
        result = num1 / num2;
    } else {
        result = "Error! Division by zero is not allowed.";
    }
} else {
    result = "Invalid operation selected.";
}

console.log("The result is: " + result);

6. Edge Cases to Consider

  • Division by Zero: Ensure your program doesn’t attempt to divide by zero.
  • Invalid Input: Add checks for invalid operations or non-numeric input if possible.
  • Negative Numbers: Handle negative numbers appropriately (e.g., -5 * -2 = 10).

What You’ve Learned

  • Arithmetic Operations: Addition, subtraction, multiplication, and division.
  • Conditional Statements: Using if-else or switch-case for decision-making.
  • User Input and Type Conversion: Taking and converting user input into numbers.

Next Steps

Once you’ve built your simple calculator:

  • Try adding more operations, such as modulus (%) or exponentiation (**).
  • Experiment with error handling to improve user experience.

Congratulations! You’re now combining multiple concepts to create interactive and functional programs. This is a big step forward in your coding journey!