Which is the difference between these two codes?

first one:

package main
import “fmt”
func main() {
var n int
fmt.Scan(&n)
var sum int
for i:=0; i<=n; i++ {
switch i%2 {
case 0:
fmt.Println(i, “even!”)
case 1:
continue
}
sum += i
}
fmt.Println(“Sum =”, sum)
}

second one:

package main
import “fmt”
func main() {
var n int
fmt.Scan(&n)
var sum int
for i:=0; i<=n; i++ {
switch i%2 {
case 0:
fmt.Println(i, “even!”)
case 1:
break
}
sum += i
}
fmt.Println(“Sum=”, sum)
}

pls if you can, give me a short explanation of the meaning of break and continue following this example, thank you.

Did you run the different codes? Did you observe any difference in the behaviour?

yes and I don’t know the meaning, the first one shows me the sum of 20 if I put 9 for wxample, instead the second one shows me 45… I think it’a a multiplication(?)

20 and 45? For 9?

I had expected the first code to show a sum of 20 and the second to show a sum of 0…

How often does each version print a number followed by “even”?

Though hard to really reason about the code for me right now. I am on a mobile and can’t run it. At the same time the missing formatting makes it hard to read the code…

5, there’s the output:

C:\Users\Ilenia\go\src\esercitazioni\lab5 esempio>go run “es 2.go”
9
0 even!
2 even!
4 even!
6 even!
8 even!
Sum = 45

so I’ve thought about a multiplication, 9*5=45, but how it works?

Okay, I had to read up about the semantics of breakin this situation first.

I assumed first that the break is bound to the loop, though it bound to the switch and something that allows to have an otherwise empty clause.

So the second version does just sums up from 0 through 9, while the first versions continue causes the current iteration of the loop to stop here and “continue” with the next one without running code “after” this. Therefore only even numbers from 0 through 9 are summed here.

This is the first piece of code:

package main

import "fmt"

func main() {
	var n int
	fmt.Scan(&n)
	var sum int
	
	for i := 0; i <= n; i++ {
		switch i % 2 {
		case 0:
			fmt.Println(i, "even!")
		case 1:
			continue
		}
		sum += i
	}
	
	fmt.Println("Sum =", sum)
}

And this is the second one:

package main

import "fmt"

func main() {
	var n int
	fmt.Scan(&n)
	var sum int

	for i := 0; i <= n; i++ {
		switch i % 2 {
		case 0:
			fmt.Println(i, "even!")
		case 1:
			break
		}
		sum += i
	}

	fmt.Println("Sum=", sum)
}

Both of them do what is expected: one prints 66 and one prints 30. This is because break will only exist the switch command, while continue will continue the for command.

1 Like