Golang program that uses switch, multiple value cases
Switch statement is a multiway branching which provides an alternative way too lengthy if-else comparisons. It selects a single block to be executed from a listing of multiple blocks on the basis of the value of an expression or state of a single variable. A switch statement using multiple value cases correspond to using more than one value in a single case. This is achieved by separating the multiple values in the case with a comma.
Example 1:
// Golang program to illustrate the
// use of switch with multiple value cases
package main
import (
"fmt"
)
func main() {
// string to input month from user
var month string
fmt.Scanln(&month)
// switch case for predicting
// seasons for month entered
// each switch case has more
// than one values
switch month {
case "january", "december":
fmt.Println("Winter.")
case "february", "march":
fmt.Println("Spring.")
case "april", "may", "june":
fmt.Println("Summer.")
case "july", "august":
fmt.Println("Monsoon.")
case "september", "november":
fmt.Println("Autumn.")
}
}
Input : january Output : Winter. Input : september Output : Autumn.
Rather than making different individual cases for months having the same season, we clubbed different months with the same output. This saves us to write redundant pieces of code.
Example 2:
// Golang program to illustrate the
// use of switch with multiple value cases
package main
import (
"fmt"
)
func main() {
// integer to input number from
// user (only 1-10)
var number int
fmt.Scanln(&number)
// switch case for predicting
// whether the number is even or odd
// each switch case has more
// than one values
switch number {
case 2, 4, 6, 8, 10:
fmt.Println("You entered an even number.")
case 1, 3, 5, 7, 9:
fmt.Println("You entered an odd number.")
}
}
Input : 6 Output : You entered an even number. Input : 5 Output : You entered an odd number.
Instead of writing 10 different cases to check whether the entered number is even or not, we could simply do the same in 2 switch cases using multiple case values.
Example 3:
// Golang program to illustrate the
// use of switch with multiple value cases
package main
import (
"fmt"
)
func main() {
// character input (a-z or A-Z)
var alphabet string
fmt.Scanln(&alphabet)
// switch case for predicting
// whether the character is
// uppercase or lowercase
// each switch case has more
// than one values
switch alphabet {
case "a", "b", "c", "d", "e", "f", "g", "h", "i",
"j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t",
"u", "v", "w", "x", "y", "z":
fmt.Println("Lowercase alphabet character.")
case "A", "B", "C", "D", "E", "F", "G", "H", "I", "J",
"K", "L", "M", "N", "O", "P", "Q", "R", "S", "T",
"U", "V", "W", "X", "Y", "Z":
fmt.Println("Uppercase alphabet character.")
}
}
Input : g Output : Lowercase alphabet character. Input : F Output : Uppercase alphabet character.