Develop an algorithm, pseudocode and flowchart to find the maximum of three numbers.
5 marks
Answer in brief
The maximum of three numbers can be found by keeping the largest value seen so far.
Algorithm
Read the values: Accept a, b and c.
Start with the first value: Set maximum = a.
Compare the second value: If b > maximum, set maximum = b.
Compare the third value: If c > maximum, set maximum = c.
Display the result: The value in maximum is the largest of the three.
Explanation
After the first assignment, maximum contains a. After comparing b, it contains the larger of a and b. After comparing c, it contains the largest of all three. A replacement is needed only when the new value is larger. Equal values do not cause a problem because the question asks for the maximum value.
Example
For a = −4, b = 9 and c = 9, maximum first contains −4. The comparison with b changes it to 9. Since c is not greater than 9, the last comparison leaves it unchanged. The output is 9.
Special cases
The method also works when all values are negative or all are equal. Do not start maximum at zero unless the input rules justify that choice. For inputs −9, −4 and −12, zero would be an incorrect answer. Starting from the first actual value avoids that mistake.
Time and space complexity
The method uses exactly two comparisons, regardless of the input values. Therefore its time complexity is O(1). It uses a fixed number of variables, so its extra space is also O(1). Finding the maximum of n values is a different problem that requires a repeated scan.
Reference tables
↔ Scroll horizontally on a small screen
Trace for -4, 9, 9
Step
Condition
maximum
Initial
Not yet compared
-4
Compare b
9 > -4 is true
9
Compare c
9 > 9 is false
9
↔ Scroll horizontally on a small screen
Maximum boundary cases
Inputs
Expected maximum
Reason to test
-9, -4, -12
-4
Detects an incorrect zero initialisation.
6, 6, 2
6
Checks a tied maximum.
3, 3, 3
3
Checks complete equality.
9, 2, 1
9
Checks that the initial candidate can remain unchanged.
/* CodeBhavya | PPS AR25 | Learning example */
#include <stdio.h>
int main(void)
{
int a = -4, b = 9, c = 9;
int maximum = a;
if (b > maximum) { maximum = b; }
if (c > maximum) { maximum = c; }
printf("Maximum = %d\n", maximum);
return 0;
}
Sample input and output
This example uses values already written in the program.
Output
Maximum = 9
Key points
Keep the maximum seen so far.
A strict comparison still works when the maximum occurs twice.
Related exam questions
Topic matches from the supplied JNTUH papers. Marks below are the printed allocations for those questions.
March/April 2023 · Q3(b) · 5 marks
What is an algorithm? Write an algorithm to find the largest of three numbers.