I recently started reading a book on data structures and it starts off with an introduction in algorithms. In one exercise it asks to prove an algorithm by induction and a loop invariant. The algorithm in pseudocode is:
Algorithm DEC2BIN(int n, int[] b)
Input: int n, array b
Output: b[i] contains the i-th bit of n's binary representation.
1: int x=n, k=0;
2:while(x>0){
3: b[k]=x%2;
4: x/=2;
5: k++;
6:}
en of DEC2BIN
I said:
Let P(n) be the statement "b contains the binary representation of n".
For n=1: It's obvious that b=[1] so, P(1).
Let P(N). How can I show P(n+1)?