For some reason the for loop wont stop once the if condition is fulfilled. How do i resolve this?