exercises and solutions

Fundamentals exercises

Fundamentals exercises build fluency with variables, arithmetic, branches, loops, and output. The learner should be able to trace the values by hand before relying on a debugger.

Practical Example

PHP example
<?php

declare(strict_types=1);

$price = 1200;
$quantity = 2;
$total = $price * $quantity;

echo 'Total: ' . $total . PHP_EOL;

// Prints:
// Total: 2400

Fundamentals exercises should practise variables, arithmetic, conditionals, loops, and output with examples that feel like small application tasks.

Include boundary cases such as an empty basket, zero quantity, or a value exactly on a discount threshold. These reveal whether the learner understands the condition rather than only the happy path.

Practice

Calculate A Discounted Basket Total

Given item totals of 1200, 800, and 500 pence, print the subtotal. Apply a ten-percent discount when the subtotal is at least 2000 pence, then print the final total.

Check the exact threshold and an empty basket.

Show solution

Use array_sum() for the subtotal and a condition using >= 2000. The supplied basket totals 2500, so the final value is 2250. An empty basket stays at 0.

The threshold case matters because > would incorrectly skip a basket worth exactly 2000.

Print An Order Summary

Given order totals of 1250, 0, and 3499 pence, print each total and classify it as empty, standard, or high-value. Treat totals of at least 3000 pence as high-value.