Golang Program to Determine Recursively Whether a Given Number is Even or Odd

Go ProgrammingServer Side ProgrammingProgramming

Steps

  • Take a number from the user and store it in a variable.
  • Pass the number as an argument to a recursive function.
  • Define the base condition as the number to be lesser than 2.
  • Otherwise, call the function recursively with the number minus 2.
  • Then, return the result and check if the number is even or odd.
  • Print the final result.
Enter a number: 124
Number is even!
Enter a number: 567
Number is odd!

Example

 Live Demo

package main
import (
   "fmt"
)
func check(n int) bool{
   if n < 2 {
      return n % 2 == 0
   }
   return check(n - 2)
}
func main(){
   var number int
   fmt.Print("Enter a number:")
   fmt.Scanf("%d", &number)
   check(number)
   if check(number)==true {
      fmt.Println("Number is even!")
   }else{
      fmt.Println("Number is odd!")
   }
}

Output

Enter a number:8
Number is even!
raja
Published on 02-Aug-2021 07:07:10
Advertisements