This version works using a while loop to calculate the index value