updated for loop to reduce the number of times the script checks for i's value