Updated for loop not working properly