This section contains the Golang switch find output programs (set 1) with their output and explanations.
Program 1:
package main
import "fmt"
func main() {
switch 30 {
case 10:
fmt.Print("TEN")
case 20:
fmt.Print("TWENTY")
case 30:
fmt.Print("THIRTY")
case 40:
fmt.Print("FORTY")
default:
fmt.Print("INVALID VALUE")
}
}
Program 2:
package main
import "fmt"
func main() {
switch 40 - 20 {
case 10:
fmt.Print("TEN")
case 20:
fmt.Print("TWENTY")
case 30:
fmt.Print("THIRTY")
case 40:
fmt.Print("FORTY")
default:
fmt.Print("INVALID VALUE")
}
}
Program 3:
package main
import "fmt"
func main() {
switch 10 {
case 20 - 10:
fmt.Print("TEN")
case 40 - 20:
fmt.Print("TWENTY")
case 60 - 30:
fmt.Print("THIRTY")
case 80 - 40:
fmt.Print("FORTY")
default:
fmt.Print("INVALID VALUE")
}
}
Program 4:
package main
import "fmt"
func main() {
switch 10 {
default:
fmt.Print("INVALID VALUE")
break
case 10:
fmt.Print("TEN")
break
case 20:
fmt.Print("TWENTY")
break
case 30:
fmt.Print("THIRTY")
break
case 40:
fmt.Print("FORTY")
break
}
}
Program 5:
package main
import "fmt"
func main() {
switch 30 {
case 10:
fmt.Println("TEN")
fallthrough
case 20:
fmt.Println("TWENTY")
fallthrough
case 30:
fmt.Println("THIRTY")
fallthrough
case 40:
fmt.Println("FORTY")
fallthrough
default:
fmt.Println("INVALID VALUE")
}
}
Answer Program 1:
Output:
Explanation:
In the above program, we created a switch block and defined 4 cases and one default case. Here case 30 matched based on the given value and printed the "THIRTY" on the console screen.
Answer Program 2:
Output:
Explanation:
In the above program, we created a switch block and defined 4 cases and one default case. Here case 20 matched based on a given value(40-20 i.e. 20) and printed the "TWENTY" on the console screen.
Answer Program 3:
Output:
Explanation:
In the above program, we created a switch block and defined 4 cases and one default case. Here case (20-10 i.e. 10) matched based on given value 10 and printed the "TEN" on the console screen.
Answer Program 4:
Output:
Explanation:
In the above program, we created a switch block and defined 4 cases and one default case. Here case 10 matched based on given value 10 and printed the "TEN" on the console screen.
Answer Program 5:
Output:
Explanation:
In the above program, we created a switch block and defined 4 cases and one default case. Here case 30, case 40, and default case will be executed because we used the fallthrough keyword. That's why all below cases will be executed after matching a correct case.