Ch. 4 - While statements and scope - Challenge 10

Why does ‘valueOnSecondDice’ have to be declared after the first while statement but not as a global variable?

while valueOnFirstDice <= 6 {
    var valueOnSecondDice = 1
    while valueOnSecondDice <= 6 {
        totalNumberOfRoles += 1
        if valueOnFirstDice + valueOnSecondDice == targetValue {
            combinationsFound += 1
        }
        valueOnSecondDice += 1
    }
    valueOnFirstDice += 1
}

Looks like it needs to be initialised to 1, so that is one place it must be accessed. You could certainly create the variable outside the top if condition and then reset the value to 1 on each loop. It’s a tradeoff - save a line of code vs. reuse a variable. The line of code less you might notice, creating a variable again you probably wouldn’t.

1 Like

Ah ok, thanks for the reply. I think I was just overthinking the issue. Thanks for steering me right.