Bug hunt: fix code you did not write

PremiumAdvanced25 min3 exercises

C is happy to compile code that does something different from what you meant. No warning, no crash, just a wrong number. This lesson is three programs like that. Every bug in it is something you have already met in this track, now hiding inside code that looks fine.

How to hunt in C:

Fix each one with the smallest change that makes it right, then say out loud why it was wrong. That sentence is the part you keep.

The rest of this lesson is Premium

Three C programs that compile and print the wrong thing: integer division, a swap that swaps copies, and sizeof on an array that has become a pointer.

Module
C Advanced: Pointers for real: passing them around, doing arithmetic with them, structs and the heap, then a bug hunt through code that compiles and lies.
Challenges
  • The average that rounds itself
  • The swap that does not
  • Counting with sizeof

First challenge: The average that rounds itself

The average of 7 and 2 is 4.5. This prints 4.0. Fix it so it prints 4.5.

£7.99 a month, or £59 a year

Premium opens every Core and Advanced lesson in all four tracks, with the editor, checker and hints, plus the bigger projects. Cancel any time.

See Premium

Or keep going for free: C Foundations and the playground are free for good.