Algorithm CS Thinking Example 3
Follow the full solution, then compare it with the other examples linked below.
Example 3
easyWrite an algorithm to find the largest number in a list of three numbers: A, B, C.
Solution
- 1 Step 1: Set largest = A.
- 2 Step 2: If B > largest, set largest = B. If C > largest, set largest = C. Output largest.
Answer
Compare each number against the current largest, updating as needed, then output the result.
Finding the maximum is a common algorithm pattern. It uses a running variable that tracks the best answer seen so far.
About Algorithm
A step-by-step set of instructions for solving a problem or accomplishing a specific task. An algorithm must be precise (every step is unambiguous), finite (it terminates after a bounded number of steps), and effective (each step can actually be carried out).
Learn more about Algorithm โMore Algorithm Examples
Example 1 easy
Write an algorithm (as numbered steps) for making a cup of tea.
Example 2 mediumHere is an algorithm: 1. Set total = 0. 2. For each number in the list [3, 7, 2, 8]: add the number
Example 4 easyA recipe says, 'Add sugar until it tastes right.' Explain why this is a poor algorithm step and rewr