Question
Topic: An algorithm to find max (or min) of any three numbers Problem statement: Given three input values (in double variables x,y,z for example), find
Topic: An algorithm to find max (or min) of any three numbers
Problem statement: Given three input values (in double variables x,y,z for example), find max (or min) of the three values.
Approach 1:
We can compare each variable to see if it is larger than each of the other two variables is. If so, its value is given to max.
// if x is larger than y and x is larger than z max is assigned x
if( (x > y) && (x > z) ) max = x;
We can proceed this way to see if y and z are max.
Code Segment 1 in the attached program implements this algorithm
Analysis: Does it work? Check with values for x,y,z as: 12.5, 35.8, -43.1 (or any three numbers which differ from each other Perhaps the results will convince that you will get correct answer.
Is there any catch? What if, two or more input numbers are same? Try inputs: 12.5, 12.5. 34.9 or 1.0, 1.0, 1.0 as inputs Do you get a correct answer? perhaps not!
Fix: use >= instead of > for comparison that will take care of situations when two or more numbers are equal.
Approach 2
Apply the fix suggested and Code Segment 2 does just that!
Try different inputs and see if the program works
Add additional code to computer min value of the three numbers and check the results.
Approach 3
Here we assign the first value to max ( max = x; )
Each time max value is compared to other variables, one at a time and it is updated when necessary.
max =x;
if( y > max ) max = y;
if (z > max) max = z; // and so on
Now at the end of this program segment, max contains the largest value of the three.
Analysis: Approach 3 keeps one variable named max to keep track of the largest number it has encountered so far It uses simple comparison operation, once per each variable to get updated when necessary it can also be extended to deal with more than three variables along the same lines. This property is known as Scalability.
Approach 2 is simpler idea, but it involves comparing each variable with each of the other variables from input.
Approach 3 is a more elegant problem-solving approach it can be used with several values of inputs also, as we will notice in future chapters.
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started