...

/

Solution Review: Season of a Month

Solution Review: Season of a Month

This lesson discusses the solution to the challenge given in the previous lesson.

There are two methods to solve this problem:

  • One is using the switch-case construct, which is the requirement of the problem statement
  • The other is using the if-else construct.

We’ll first discuss the switch-case solution.

Using switch-case construct

Press + to interact
package main
import "fmt"
func main() {
fmt.Printf(Season(3)) // calling function to find the season
}
func Season(month int) string {
switch month { // switch on the basis of value of the months(1-12)
case 12,1,2: return "Winter" // Jan, Feb and Dec have winter
case 3,4,5: return "Spring" // March, Apr and May have spring
case 6,7,8: return "Summer" // June, July and Aug have summer
case 9,10,11: return "Autumn" // Sept, Oct and Nov have autumn
default: return "Season unknown" //value outside [1,12], then season is unkown
}
}

As you can see, we declare a function Season at line 9, which takes an integer value that represents a month as an input parameter. That parameter is the value of month. As per requirement, we add switch month to switch on the basis of the value of the month. There are five cases in total along with the default case.

  • We make the first case at line 11 for the season of Winter. We return Winter for months of Jan, Feb, and Dec by using values 1,2 ...