Dividing Only When It Is Safe

Easy

Read two whole numbers with a single scanf call, then decide what to print with one if / else if / else chain that has exactly three branches. If scanf did not convert two values, print "error: expected two numbers". Otherwise, if the divisor is 0, print "error: cannot divide by zero". Otherwise print the quotient and the remainder in the form "84 / 5 is 16 remainder 4". The order of the branches is the exercise. Dividing by zero is undefined behaviour, so the only moment you can do anything about it is before the division runs, and the same goes for computing with a variable scanf never wrote. Watch the negative test case too: the remainder takes the sign of the dividend, so -7 / 2 is -3 remainder -1, exactly as lesson 2 showed. One note on this exercise's exit status. The lesson's version used return 1 to tell the operating system that a run failed, which is what a real program does; here the checker compares only what you print, so keep the single return 0 at the end of main and let the chain choose the message.

Success Criteria

Your code must pass 5 test case(s) to complete this exercise. 3 hint(s) are available if you need help.

Sign in to track your progress

You can work on exercises as a guest, but sign in to track your progress and save your submissions.

This platform is built by its community

Every lesson, project, and tool on HelloC++ is funded by sponsors. Join them and help shape what we build next.

Become a Patron