Logic Problem using a for loop