Why the variable is not being updated inside the for loop?

There is a variable call shoot in the func main that is not being updated. So in the code below there is an inner for loop that ends at value 7 ( i := 0; i < 8; i++), each iteration of the loop represents a mountain and each iteration has a variable mountainH which represents the current mountain height, so what the exercise is asking is for the heightest mountain to shoot in order to win. The shoot variable is never updated, would you please help on this?

    func main() {

    for {
        shoot := 0 // this is the variable that I want to use to update it
        hightestMountain := 0
        for i := 0; i < 8; i++ {

            var mountainH int

            if mountainH > hightestMountain {  //mountainH is never 0 because the game engine gives to it the corresponding value in each iteration
                hightestMountain = mountainH
                shoot = i  // here where I want to update it
        fmt.Println(shoot)  // but I always get 0

You can test this code at the game board here: Game board

Don’t you need to move fmt.Scan(&mountainH) before the if statement?

If that’s the bit that updates the variable from the game engine, then currently you are creating the variable, doing the test, then updating, and finally losing the value as the code moves to the next iteration of the for-loop. Instead you need to create the variable, update it, and then test.

1 Like

Thank you very very much, and I am sorry because I am just beginning with golang and didn’t know that this fmt.Scan had such an impact in the code.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.