Getting stuck in a loop even when the conditions for the statement changes