extremum.c

Algorithm:

  • Read 5 numbers from the user
  • Find the smallest and the greatest
  • Output the smallest and greatest number

Some comments

  • To achieve better readability, it may be advisable to explicitly write down your variables and possibly also comment on what variable is used for which purpose.
  • Repeated actions can be abstracted to some extent. In this case we have described finding the maximum value as a repeated action from the previous column (finding minimum), also stating the differences compared to it.
  • The numbers are stored in an array. Arrays are indexed and the indexes start from zero.
  • In the algorithm I have shown both the human-readable text and the lines that one could use to implement this in code (e.g. i = 0, i++, i < 5, largestNum = num[i] etc.). It’s however more important to have the textual explanations that another human can read, indicating the purpose of each action. The code lines are just for help.
  • The algorithm principle is that before doing any comparisons, we pick one number that we say is the smallest / greatest number. Only after that we can start to compare the rest of the array to see if any other number is greater or smaller than the one we picked. If we happen to find such a number, we will replace what we had stored so far with the new lowest / highest number and continue comparing with that.
  • In this solution we assumed that the first element of the array (index 0) was the smallest / largest number from that array before checking the others. This is why the loops for the comparison start from the second element (i = 1) – we don’t need the compare the number we picked as the initial assumption. However it should be noted that other loops that we use for input and output will still need to start from the first element (i = 0), as in there we are addressing the entire array
  • Common mistake: The smallest / largest element is fixed with some number in code that has nothing in common with the array. E.g. We are looking for the biggest element in the array and we initialize the value of our maximum to 0, assuming that everything will be larger than that. The makes our program fail to find the correct answer if all numbers are negative. The initial value for the minimum and maximum must always be picked from the array

Recommendations on writing the code:

  • Try to figure out which parts from the UML are the loop conditions and which are just normal conditionals (just if statements). How to identify those?
  • If statement does not need an else statement to accompany it. If there is no reason to do so, don’t write one.
  • Tips for the advanced task: if both parts of the division are integers, the answer will be an integer.

Code sample

This is the base code written during the class. It contains reading of the array, finding the smallest element and its index and outputing those results and the initial array.