Programming Example
Simple Calculator using PHP
Simple Calculator using PHP
<?PHP
class Calculator {
public function add($number1, $number2){
if(is_numeric($number1) && is_numeric($number2)){
return $number1+$number2;
}else{
echo "values should be numeric.";
}
}
public function subtract($number1, $number2){
if(is_numeric($number1) && is_numeric($number2)){
return $number1-$number2;
}else{
echo "values should be numeric.";
}
}
public function multiply($number1, $number2){
if(is_numeric($number1) && is_numeric($number2)){
return $number1*$number2;
}else{
echo "values should be numeric.";
}
}
public function divide($number1, $number2) {
if(is_numeric($number1) && is_numeric($number2) && $number2 != 0){
return $number1/$number2;
}else{
echo "Values should be numeric and divisor shouldn't be zero.";
}
}
}
$calc = new Calculator;
echo $calc->add(1,3);
echo "<br>";
echo $calc->subtract(4,3);
echo "<br>";
echo $calc->multiply(2,3);
echo "<br>";
echo $calc->divide(10,2);
?>
4
1
6
5
First read the algorithm, then study the program code line by line. After that, compare the code with the output and finally go through the explanation. This approach helps learners understand both the logic and the implementation properly.
After understanding this example, try to rewrite the same program without looking at the code. Then change some values or logic and run it again. This helps improve confidence and keeps learners engaged on the page for longer.