×

Golang Tutorial

Golang Reference

Golang Programs

Golang Practice

Golang Miscellaneous

Golang Switch | Find Output Programs | Set 1

This section contains the Golang switch find output programs (set 1) with their output and explanations.
Submitted by Nidhi, on August 11, 2021

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")
	}
}

Output:

THIRTY

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.


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")
	}
}

Output:

TWENTY

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.


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")
	}
}

Output:

TEN

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.


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
	}
}

Output:

TEN

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.


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")
	}
}

Output:

THIRTY
FORTY
INVALID VALUE

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.

Golang Find Output Programs »





Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.