r/eli5_programming • u/IlliterateAdult • 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
View all comments
Show parent comment
1
u/Screwedsicle Jun 13 '21
Your increment might be in the wrong place, or you have a
loopcommand of some kind in there that brings you back to the beginning. In general,ifblocks don't loop and only get evaluated once;whileblocks loop and get evaluated until the condition is no longer met. If you can post all your code that might help us point you in the right direction.