An algorithm is a set of instructions for performing a task. For instance, the following two algorithms determine if a nonnegative integer is odd or even:
\textbf{Data}: a nonnegative integer n
\textbf{Result}: whether n is odd or even
\textbf{while} n \geq 0 \textbf{do}
\quad \textbf{if} n=0 \textbf{then}
\quad \quad \textbf{return} n is even
\quad \textbf{end}
\quad \textbf{else if} n=1 \textbf{then}
\quad \quad \textbf{return} n is odd
\quad \textbf{end}
\quad \textbf{else}
\quad \quad n \leftarrow n-2
\quad \textbf{end}
\textbf{end}
\textbf{Data}: a nonnegative integer n
\textbf{Result}: whether n is odd or even
\textbf{for} i=0,2,4,6, \ldots \textbf{do}
\quad \textbf{if} n=i \textbf{then}
\quad \quad \textbf{return} n is even
\quad \textbf{end}
\quad \textbf{else if} n=i+1 \textbf{then}
\quad \quad \textbf{return} n is odd
\quad \textbf{end}
\textbf{end}
We will now detail a common convention in writing algorithms called pseudocode. It is not required that you follow these conventions, but you must be able to clearly describe the steps of your algorithms. There are only a few conventions that we need to introduce:
Algorithms generally require correctness - the algorithm always outputs the right answer - and termination - the algorithm doesn’t run infinitely.
Prove that the above two algorithms are correct and always terminate.