Project: Calculator
Overview of the 5-lesson calculator project: you will operate on two numbers and an operator.
Project: Calculator
In this 5-lesson project you'll build a calculator. Each lesson adds one piece, and by the final lesson you'll have a complete app.
You'll use what you learned before:
- variables with the
$sign - output with
echo - string and int types
- variable concatenation
You'll also learn the if/elseif structure and arithmetic operators in this project. Ready? Let's start.
The calculator flow
The calculator works in four steps:
- Input: two numbers are taken.
- Operation: an operator is chosen (
+,-,*,/). - Compute: the result is found based on the operator.
- Output: the result is printed.
In the first lesson we'll just take one number and print it. The next lessons add the operator, the second number and the compute step. Each lesson grows the calculator by one step.
Exercise Declare the first number and print it
In this lesson you'll write the first piece of the calculator. Assign 25 to the $first variable and print it with echo.
Show example solution
Declare the variable with $ and print it with echo.
Example solution:
<?php
// The first number entered by the user
$first = 25;
echo $first;
Test yourself
-
What does a calculator need first to work?
- A file
- Two numbers and an operation
- A database
- A class
Show answer
Two numbers and an operation — A calculator takes two numbers and performs an operation between them.
-
Match each calculator step to its description
- Input
- Two numbers are taken
- Operation
- Operator is chosen
- Compute
- Result is found
- Output
- Result is printed
-
Assign 25 to the first number variable
<?php $first = ____; echo $first; ?>Show answer
<?php $first = 25; echo $first; ?>