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
2
u/IlliterateAdult Jun 13 '21
Thank you both for the response. I have edited the original post to include the full code.
Your explanations of “if” and “while” make sense to me, but the section of code I’m having trouble with seems to contradict your explanations. When “primeLoop” starts with ”if”, the function bigLoop() will run a varying number of times until all the gems are collected, and terminates once the amount is reached. But when I start “primeLoop ” with ”while”, the section runs indefinitely.