TryBugHunt
cppInfinite loopEasy

Next power of two never returns

BugFind the bug and fix the code

What it should do

nextPowerOfTwo(n) returns the smallest power of two (1, 2, 4, 8, ...) that is at least n, for n from 1 to 1000. Example: nextPowerOfTwo(5) → 8

What happens instead

nextPowerOfTwo(5) never returns and the run times out.

int nextPowerOfTwo(int n) {
    int p = 0;
    while (p < n) {
        p *= 2;
    }
    return p;
}

Test a custom input to verify an edge case (e.g. empty lists, negative numbers, duplicates).

⏱️0:00
Hints
🏆 0 hints = Flawless Solve
Think & Test Cooldown
2:00 remaining

Take a moment to read the bug symptom and trace the code with Run & Check before unlocking Hint 1.

Hint 2
Unlocks after Hint 1
Hint 3
Unlocks after Hint 2

This bug belongs to the infinite loops pattern

The loop condition never becomes false, so the program runs until it is stopped.

What you'll practise

An easy C++ debugging exercise about infinite loops: the loop condition never becomes false, so the program runs until it is stopped.

The checks your fix must pass

Signs of this kind of bug

Spoiler: why this bug happens(try it first; the hints get warmer one at a time)

What went wrong: p starts at 0, and 0 * 2 is still 0. p never grows, so p < n stays true forever.

The fix: Start at the first power of two, p = 1.

Remember: A loop that multiplies must not start at 0, just as a loop that adds must not add 0. When a loop hangs, check that the variable in its condition really changes on every pass.

The pattern behind it: infinite loops.

More infinite loops to practise

Embed this challenge on your site

Paste this into any web page or blog post. Visitors fix the bug right there, in their browser.

<iframe src="https://trybughunt.com/embed/585b5062-113b-4e8e-9ef5-7d380c5e5825" title="Debugging challenge: Next power of two never returns" width="100%" height="580" loading="lazy" style="border:1px solid #d4d4d8;border-radius:12px;max-width:760px"></iframe>
<p style="font-size:14px">Debugging challenge from <a href="https://trybughunt.com/challenges/585b5062-113b-4e8e-9ef5-7d380c5e5825">TryBugHunt</a></p>