Exercise 6
September 27, 2019
Today’s task is a beginning programmer’s exercise from Bjarne Stroustrup’s book Programming: Principles and Practice Using C++:
Write a program that prompts the user to enter 3 integer values, and then outputs the values in numerical sequence separated by commas. So: if the user enters the values 10 4 6, the output should be 4, 6, 10. If two values are the same, they should just be ordered together. So, the input 4 5 4 should give 4, 4, 5.
Your task is to write the indicated program; you may use C++ or any other language, but your solution should be at the level of a beginning programmer who has not yet learned about arrays or user-defined functions. When you are finished, you are welcome to read or run a suggested solution, or to post your own solution or discuss the exercise in the comments below.
Here’s another approach (omitting the reads and written in Python)
The last elif-clause can become an else-clause. This does more tests than your/Stroustrup’s solution, but it is very easy to check it for correctness: just see that each of the print statements satisfies the relational tests, and that there are 3! tests altogether. It also satisfies the rule in The Elements of Programming Style: flatten out multiple tests when possible.
Oops, got messed up there:
Here’s another approach (omitting the reads and written in Python)
The last elif-clause can become an else-clause. This does more tests than your/Stroustrup’s solution, but it is very easy to check it for correctness: just see that each of the print statements satisfies the relational tests, and that there are 3! tests altogether. It also satisfies the rule in <i>The Elements of Programming Style: flatten out multiple tests when possible.
Here’s a solution in Python.
Example Usage:
I would encourage the student to first of all write a nice simple and obviously correct solution, without being concerned with efficiency:
We have one clause for each of the 6 possible orderings, and the condition is just that a,b and c do have that ordering, so barring simple typos, not much can go wrong. The final else clause is just there to catch such errors (a more sophisticated programmer might use an assertion here).
For most purposes, that would be the perfect solution, but a more enthusiastic student might observe that we might do many more comparisons that necessary, in which case, they might get extra marks for something like this:
In two of the six cases, only two comparisons need to be done, and the other four cases just require one extra check. The student has annotated each of the main branches with the cases that will be handled by that branch, making it easy to check all cases are handled correctly; also the second branch is the same as the first, with a and b exchanged, making use of the symmetry of the situation and further increasing confidence. Testing will be made easier by having the first, more obviously correct function to compare against.