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.
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(?)
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…
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.
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.