Updated main algorithm to use for loops