Can You Break My Code?

Revision en1, by ChallaAjay, 2026-10-10 15:17:50

Okay, here's a challenge.

The code below is supposed to find the maximum element in a non-empty array. It compiles, and it looks pretty normal.

int ans = 0;

for (int i = 0; i < n; i++) {
    if (a[i] > ans) {
        ans = a[i];
    }
}

cout << ans << '\n';

Find a valid input for which this code fails.

Rules: - Give the smallest counterexample you can find. - Explain why the output is wrong. - Bonus: fix it without changing the overall approach.

Try to find the bug before opening the comments.

Let's see who catches it first

History

 
 
 
 
Revisions
 
 
  Rev. Lang. By When Δ Comment
en1 English ChallaAjay 2026-10-10 15:17:50 600 Initial revision (published)