Discrete Mathematics and Its Applications, Seventh Edition

Published by McGraw-Hill Education
ISBN 10: 0073383090
ISBN 13: 978-0-07338-309-5

Chapter 3 - Section 3.1 - Algorithms - Exercises - Page 202: 8

Answer

procedure evenmax$(a_1, a_2, a_3, ..., a_n :$ a list of n integers$)$ index$:= -1$ for $i:=0$ to $n$ $\space\space\space$ if $a_i$ is even $\space\space\space$ $\space\space\space$ if index equals $-1$ then index $:=i$ $\space\space\space$ $\space\space\space$ else if $a_i > a_{index}$ then $index:=i$ if index is $-1$ then return $0$ {This is because the question requests that $0$ be returned if no even numbers are found} else return index.

Work Step by Step

The algorithm attempts to find the index of the largest even number. It does this by iterating through the list and checking if the number is both even and larger than the previous largest even number encountered. Notice the edge case that when we first meet an even number, we have nothing to compare it so we have to assign its index directly. Notice also that the index was set to $-1$ to make it clear if index was updated or not during the algorithm steps. If it didn't get updated, we return a $0$ as the question specified. Finally, notice that for complex operations, we specified them in words rather than writing them mathematically. This is because testing for evenness and oddness haven't been covered yet. They are usually checked for using the modulus operator (in chapter 4) but is not required at this level yet.
Update this answer!

You can help us out by revising, improving and updating this answer.

Update this answer

After you claim an answer you’ll have 24 hours to send in a draft. An editor will review the submission and either publish your submission or provide feedback.