Sunday, September 30, 2012

Two ways to find the max of 5 numbers

It started as an experiment to find out which of the two ways (I could think of) how to find the max of 5 numbers. I wanted to make this language agnostic, in other words, no library functions or language specific features.

The variable nCount was to find out how many conditions are being executed. Method 2 seems more complex. But is it better in terms of number of conditions executed to find the answer.

Output from few runs:

$ java LargestIn5Enter the first number: 1Enter the second number: 2Enter the third number: 3Enter the fourth number: 4Enter the fifth number: 55 is the largestnCount = 4 5 is the largestnCount = 4 $ java LargestIn5Enter the first number: 2Enter the second number: 3Enter the third number: 4Enter the fourth number: 5Enter the fifth number: 15 is the largestnCount = 4 5 is the largestnCount = 4 $ java LargestIn5Enter the first number: 3Enter the second number: 4Enter the third number: 5Enter the fourth number: 1Enter the fifth number: 25 is the largestnCount = 4 5 is the largestnCount = 4 $ java LargestIn5Enter the first number: 4Enter the second number: 5Enter the third number: 1Enter the fourth number: 2Enter the fifth number: 35 is the largestnCount = 4 5 is the largestnCount = 4 $ java LargestIn5Enter the first number: 5Enter the second number: 1Enter the third number: 2Enter the fourth number: 3Enter the fifth number: 45 is the largestnCount = 4 5 is the largestnCount = 4 $

Sometimes, the more complex looking code is not necessarily the more optimal one.