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/[deleted] Jun 13 '21
I think what you're missing here is two things.
First,
foris also a type of loop, likewhile.Second, you can nest structures. If I put my cat in my car and drive downtown, does that mean my cat is able to achieve a top speed of 150 km/h? Absolutely not! But my car is able to reach that speed, and anything inside the car when it moves at 150 km/h will be carried along for the ride. If I write an
ifstatement, that statement can only execute once. But if I put theifinside awhileloop, then theifwill execute once for each repetition of thewhileloop. That doesn't mean anifstatement is a loop! I have just put theif(my cat) inside awhile(my car) that is able to repeat (reach 150 km/h).