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
0
u/IlliterateAdult Jun 13 '21
I appreciate the response, but I’m afraid it raises more questions, honestly!
Initially, the condition (
numberOfGems < totalGems) will always be true, as numberOfGems is assigned as 0, whereas totalGems should always be a positive integer. So, my understanding is the “if” portion will run initially (as the condition starts as true), but then would not reassess the conditions and simply run until terminated .My misunderstanding of “while” is that a ”while” loop will initially see the condition is true, run the loop one time, check to see if the condition is true a second time, then run the loop a second time, until the “while” condition is false.