Calculator
Difficulty: Medium
In this challenge, you'll build a basic calculator app that allows users to perform arithmetic operations between two numbers. The app will let users input numbers dynamically, choose an operation, and compute the result. This exercise emphasizes UI layout, state management, and event handling.
Overview
This is a single-screen application with the following components:
- Equation Display – Shows the numbers and operation in real-time as the user types (e.g.,
"5 + 8"). - Number Pad – A 3x4 grid for entering numbers (
0-9), along with a clear button (C) and an equals button (=) - Operations Row – Buttons for selecting addition (
+), subtraction (−), multiplication (×), and division (÷).
User Interaction Flow
- Enter the first number using the number pad.
- Select an operation (
+,−,×,÷). - Enter the second number using the number pad.
- Press the "=" button to compute and display the result.
Handling Multiple Operations - If the user starts a new operation after completing one, the previous operation should be computed immediately, and the result should be used for the next step. Example: The user enters 1 + 5, then presses "×" instead of "=". The display should update immediately to 6. The user can then continue entering × 10 =, which results in 60.
Requirements
UI Layout
Equation Display (Top) – Shows the current input and operation.
8 × 10Number Pad Grid (Middle) –
7 8 9
4 5 6
1 2 3
C 0 =
Cbutton clears the entire equation.=button calculates and displays the result.
Operations Row (Bottom) –
+ - × ÷
Error Handling
Prevent invalid inputs, such as:
- Multiple consecutive operators (e.g.,
"5 ++ 8"should not be allowed). - Starting an equation with an operator (e.g.,
"+ 8"should not be allowed). - Division by zero, which should display
"Error"instead of crashing.
Above & Beyond
Once the core functionality is complete, consider adding:
- Decimal Support – Allow users to enter decimal numbers (
3.14). - Backspace Functionality – Let users delete the last entered digit.