r/eli5_programming • • Jun 13 '21

ELI5 ‘if’ vs ‘while’ loops

Can someone help me understand why this while loop runs indefinitely instead of breaking:

primeLoop: while numberOfGems < totalGems {
    for i in 1 ... totalGems {
        bigLoop()
        if numberOfGems == totalGems{
            break primeLoop
        }
    }
}

Whereas changing the while to if in line 1 causes the loop to terminate at the expected time? My understanding of while loops are that they run while the condition is true, and automatically end once the condition is false. Is there a general rule of thumb as to when I should use while or if?

Full code :

let totalGems = randomNumberOfGems
let first = Expert()
let second = Expert()
var numberOfGems = 0
world.place(first, facing: north, atColumn: 0, row: 4)
world.place(second, facing: north, atColumn: 3, row: 0)

func turnAround(item:Expert){
    item.turnLeft()
    item.turnLeft()
}

func stepOff(item:Expert){
    item.turnRight()
    item.moveForward()
    item.collectGem()
    turnAround(item: item)
    item.moveForward()
    item.turnRight()

}
func mainMove(item: Expert) {
    for i in 1 ... 6 {
        if item.isOnGem{
            item.collectGem()
            numberOfGems += 1
        }
        if !item.isBlockedRight{
            stepOff(item: item)
        }
        item.moveForward()

    }
}

func bigLoop() {
    first.turnLock(up: true, numberOfTimes: 1)
    mainMove(item: second)
    turnAround(item: second)
    mainMove(item: second)
    turnAround(item: second)
}
primeLoop: if numberOfGems < totalGems {
    for i in 1 ... totalGems {
        bigLoop()
        if numberOfGems == totalGems{
            break primeLoop
        }
    }
}
2 Upvotes

12 comments sorted by

View all comments

Show parent comment

1

u/Suspicious-Service Jun 13 '21

", but then would not reassess the conditions and simply run until terminated ." That is what's happening. But the thing is, you have another loop inside the if statement. That "for" loop will execute it's own specific number of times. When it's an if statement, the loop only iterates X amount of times. But when you have a 'while' instead of the 'if', the 'for' iterates X times each iteration of the 'while'

2

u/IlliterateAdult Jun 13 '21

This does help clear things up for me - thanks!