corrected for loop exit condition