Learn to Code 2 > Variables > Three Gems, Four Switches

My while loop continues execution after reaching gemsCollected = 3 if I use OR logical operator (||) and stops execution if I use AND logical operator (&&). IMHO it should be the other way around, right?

var gemsCollected = 0

var switchesToggled = 0

while gemsCollected < 3 || switchesToggled < 4 {
    
    moveForward()
    if gemsCollected < 3 && isOnGem {
        collectGem()
        gemsCollected = gemsCollected + 1
    } else if switchesToggled < 4 && isOnClosedSwitch {
        toggleSwitch()
        switchesToggled = switchesToggled + 1
    } else if isBlocked && !isBlockedRight {
        turnRight()
    } else if isBlocked && !isBlockedLeft {
        turnLeft()
    }
    
}

Accepted Reply

The behaviour you are seeing is actually as expected, due to the way logical operators work in programming.

When you use an OR (||) operator in your while condition, it means the loop will continue to execute as long as at least one of the conditions is true. So in your case, the loop will keep running if either gemsCollected < 3 OR switchesToggled < 4.

Therefore, even if you have collected 3 gems, but have not toggled 4 switches, the loop will continue to run because the switchesToggled < 4 condition is still true.

Add a Comment

Replies

The behaviour you are seeing is actually as expected, due to the way logical operators work in programming.

When you use an OR (||) operator in your while condition, it means the loop will continue to execute as long as at least one of the conditions is true. So in your case, the loop will keep running if either gemsCollected < 3 OR switchesToggled < 4.

Therefore, even if you have collected 3 gems, but have not toggled 4 switches, the loop will continue to run because the switchesToggled < 4 condition is still true.

Add a Comment