Topic 20 of 48 · Full Stack Essentials

Arithmetic Operations with while and if conditions (Prime, odd, even)

Lesson TL;DRTopic 5: Arithmetic Operations with while and if conditions (Prime, odd, even) 📖 5 min read · 🎯 intermediate · 🧭 Prerequisites: phpwithupdatedelete, whileifconditionifelseelseif Why this matters He...
5 min read·intermediate·php · arithmetic · loops · prime-numbers

Topic 5: Arithmetic Operations with while and if conditions (Prime, odd, even)

📖 5 min read · 🎯 intermediate · 🧭 Prerequisites: php-with-update-delete, while-if-condition-if-else-else-if

Why this matters

Here's the thing — when you write a program that checks numbers, you're not just doing math. You're teaching the computer to think about numbers the way you do. Is this number divisible by 2? Is anything other than 1 and itself dividing into it cleanly? These are the kinds of questions that power real systems — billing software, game mechanics, data filters. In this lesson, you'll combine while loops with if conditions to scan through a range of numbers and automatically sort them into prime, odd, and even. Once you see this pattern click, a whole category of problems opens up.

What You'll Learn

  • What prime, odd, and even numbers are and how to detect them programmatically
  • How to write a reusable isPrime() function in PHP using a for loop and sqrt()
  • How to use a while loop to iterate over a numeric range
  • How to nest if / else conditions inside a loop to classify each number simultaneously

The Analogy

Think of a postal worker sorting a large bag of numbered parcels. For every parcel they pick up, they run three quick checks: "Is this number special — divisible only by itself and 1 (prime)? Is it cleanly divisible by 2 (even)? Or does it leave a remainder when halved (odd)?" The worker doesn't open a new bag per check — they perform all three tests on each parcel before setting it down and picking up the next one. Your while loop is the postal worker; your if conditions are the three-question checklist applied to every number in the range.

Chapter 1: The Basics of Arithmetic Operations

Before writing any code, the trainer grounded the class in the definitions that drive all three checks.

Prime Numbers

A prime number is any integer greater than 1 whose only positive divisors are 1 and itself.

  • 2, 3, 5, 7, 11, 13 … are prime.
  • 4 is not prime because 4 ÷ 2 = 2 (a divisor other than 1 and itself).
  • 1 is not prime by definition.

The efficient way to test primality is to check divisors only up to sqrt(number). If no integer in the range [2, √n] divides n evenly, n is prime. Checking beyond the square root would be redundant — every factor pair has one member ≤ √n.

Odd and Even Numbers

TypeRuleExamples
Evennumber % 2 == 0 (divisible by 2)2, 4, 6, 8 …
Oddnumber % 2 != 0 (leaves remainder 1)1, 3, 5, 7 …

The modulo operator % returns the remainder after division. It is the single tool needed for both classifications.

Key PHP Operators Used

  • % — modulo (remainder)
  • sqrt() — built-in square root function
  • <= — less-than-or-equal comparison
  • == — equality check
  • ++ — post-increment (advance the counter by 1)

Chapter 2: Implementing the Logic

The class broke the problem into two pieces: a reusable primality function and a range-walking loop.

The isPrime() Function

<?php
function isPrime($number) {
    if ($number <= 1) {
        return false;
    }
    for ($i = 2; $i <= sqrt($number); $i++) {
        if ($number % $i == 0) {
            return false;
        }
    }
    return true;
}
?>

Step-by-step logic:

  1. Immediately return false for any number ≤ 1 — neither 0 nor 1 is prime.
  2. Loop from 2 up to and including sqrt($number).
  3. Inside the loop, if $number % $i == 0, a divisor was found — return false.
  4. If the loop completes without finding a divisor, return true.

Using a while Loop with if Conditions

With isPrime() defined, the class wired it into a range iteration:

<?php
// Define the range
$start = 1;
$end   = 50;

// Initialize the counter
$current = $start;

// Loop through the range
while ($current <= $end) {

    // Check if the number is prime
    if (isPrime($current)) {
        echo "$current is a prime number.<br>";
    }

    // Check if the number is even
    if ($current % 2 == 0) {
        echo "$current is an even number.<br>";
    } else {
        // If it's not even, it must be odd
        echo "$current is an odd number.<br>";
    }

    // Increment the counter
    $current++;
}
?>

Notice that the prime check and the even/odd check are independent if blocks. A number can satisfy both: 2 is prime and even. Both lines print. The else on the even/odd block is safe because every integer is exactly one of the two — there is no third category to worry about.

flowchart TD
    A[Start: current = 1] --> B{current <= 50?}
    B -- No --> Z[End]
    B -- Yes --> C{isPrime(current)?}
    C -- Yes --> D[echo prime message]
    C -- No --> E[skip prime message]
    D --> F{current % 2 == 0?}
    E --> F
    F -- Yes --> G[echo even message]
    F -- No --> H[echo odd message]
    G --> I[current++]
    H --> I
    I --> B

Chapter 3: Putting It All Together

Here is the complete, self-contained PHP script combining the isPrime() function with the while loop and if conditions:

<?php
function isPrime($number) {
    if ($number <= 1) {
        return false;
    }
    for ($i = 2; $i <= sqrt($number); $i++) {
        if ($number % $i == 0) {
            return false;
        }
    }
    return true;
}

// Define the range
$start   = 1;
$end     = 50;
$current = $start;

// Loop through the range
while ($current <= $end) {

    // Check if the number is prime
    if (isPrime($current)) {
        echo "$current is a prime number.<br>";
    }

    // Check if the number is even
    if ($current % 2 == 0) {
        echo "$current is an even number.<br>";
    } else {
        // If it's not even, it must be odd
        echo "$current is an odd number.<br>";
    }

    $current++;
}
?>

Sample output for the first few iterations:

1 is an odd number.
2 is a prime number.
2 is an even number.
3 is a prime number.
3 is an odd number.
4 is an even number.
5 is a prime number.
5 is an odd number.
6 is an even number.
...

Notice that 2 generates two lines — it is both prime and even. That is correct behavior, not a bug.

🧪 Try It Yourself

Task: Modify the script to also print a separate summary at the end: the total count of prime numbers, even numbers, and odd numbers found in the range 1–50.

Success criterion: After all the per-number lines, you should see three lines like:

Total primes: 15
Total evens: 25
Total odds: 25

Starter snippet — add three counters before the loop and increment them inside:

<?php
function isPrime($number) {
    if ($number <= 1) { return false; }
    for ($i = 2; $i <= sqrt($number); $i++) {
        if ($number % $i == 0) { return false; }
    }
    return true;
}

$start        = 1;
$end          = 50;
$current      = $start;
$primeCount   = 0;
$evenCount    = 0;
$oddCount     = 0;

while ($current <= $end) {
    if (isPrime($current)) {
        echo "$current is a prime number.<br>";
        $primeCount++; // increment here
    }
    if ($current % 2 == 0) {
        echo "$current is an even number.<br>";
        // TODO: increment evenCount
    } else {
        echo "$current is an odd number.<br>";
        // TODO: increment oddCount
    }
    $current++;
}

// TODO: echo the three summary lines
?>

Fill in the two TODOs and add the summary echo statements.

🔍 Checkpoint Quiz

Q1. Why does the isPrime() function only loop up to sqrt($number) instead of up to $number - 1?

A) PHP's for loop cannot count that high
B) Any factor larger than √n must be paired with a factor smaller than √n, so checking beyond √n is redundant
C) sqrt() is the only math function available in PHP
D) It prevents the number from being modified by the loop

Q2. Given this snippet, what is printed when $current is 6?

if (isPrime($current)) {
    echo "$current is a prime number.<br>";
}
if ($current % 2 == 0) {
    echo "$current is an even number.<br>";
} else {
    echo "$current is an odd number.<br>";
}

A) 6 is a prime number. only
B) 6 is an even number. only
C) 6 is a prime number. and 6 is an even number.
D) Nothing — 6 is skipped

Q3. What would happen if you changed while ($current <= $end) to while ($current < $end) and $end = 50?

A) The script would run forever
B) The number 50 would never be processed
C) The loop would start at 0 instead of 1
D) No change — < and <= are equivalent for integers

Q4. You need to adapt this script to print only numbers that are both prime and odd (i.e., exclude 2). Which condition correctly gates the output?

A) if (isPrime($current) || $current % 2 != 0)
B) if (isPrime($current) && $current % 2 != 0)
C) if (!isPrime($current) && $current % 2 == 0)
D) if (isPrime($current) == $current % 2)

A1. B — Every composite number n has at least one factor ≤ √n. If none exist in that range, no factor exists at all, so n is prime. Iterating beyond √n wastes cycles and produces the same result.

A2. B — 6 is not prime (6 % 2 == 0 and 6 % 3 == 0), so the prime block is skipped. 6 is even (6 % 2 == 0), so "6 is an even number." prints. The else branch is not reached.

A3. B — With strict less-than, the loop exits as soon as $current reaches 50 without processing it. Changing <= to < silently drops the last value in the range.

A4. B — The && (AND) operator requires both conditions to be true simultaneously: the number must be prime and must leave a remainder when divided by 2. This correctly excludes 2 (even prime) while including 3, 5, 7, 11, etc.

🪞 Recap

  • A prime number is any integer > 1 divisible only by 1 and itself; testing divisors up to sqrt(n) is sufficient and efficient.
  • Even numbers satisfy n % 2 == 0; anything else is odd — these are mutually exclusive, making if/else the right tool.
  • A while loop iterates over a range by comparing a counter variable to an end boundary and incrementing it each pass.
  • Because the prime check and the even/odd check are independent if blocks, a single number (like 2) can satisfy and print both.
  • Extracting the primality test into its own function (isPrime()) keeps the loop body readable and makes the logic reusable.

📚 Further Reading

Like this topic? It’s one of 48 in Full Stack Essentials.

Block your seat for ₹2,500 and join the next cohort.