Thursday, December 13, 2018

golang example - program to check number/integer even or odd

In this blog post, we will learn  two programs
The first program is how to check input number is even or odd.the second program is how to check given array or slice of number for even or odd numbers.
Even number is a number divisible to 2 is zero that means the number is even if operation modulus operator divisible by 2 is remainder=0

Example to check Number is even or odd

In the below program. Scanlin function is used to take the input number from user console ie command line. user entered a number is stored in number variable

Now checking number is even or odd, we used modulus operator % and check remainder is zero with divisible by 2. conditional structure if else statement  is used. the if the number is divisible by 2, then it is even number, an else odd number
package main

import (
 "fmt"
)

func main() {
 fmt.Print("Please enter first number: ")
 var number int
 fmt.Scanln(&number) // take input from user
 if number%2 == 0 {
  fmt.Printf("%v is a Even Number", number)
 } else {
  fmt.Printf("%v is a Odd Number", number)
 }
}
When you compile and run the program, the output will be:
Please enter first number: 23
23 is a Odd Number
Please enter first number: 54
54 is a Even Number

Example to check array or slices of Number are even or odd 

First array/slice is created with initialized with values. You can learn more about slice
Iterate the slice using for loop and for loop with range form  . Each number is checked for an odd or even number and printed the result to the console
package main

import (
 "fmt"
)

func main() {
 var numbs = []int{51, 4, 5, 6, 24, 11}
 for _, number := range numbs {
  if number%2 == 0 {
   fmt.Printf("%v is a Even Number\n", number)
  } else {
   fmt.Printf("%v is a Odd Number\n", number)
  }
 }
}
Output of the above program is
51 is a Odd Number
4 is a Even Number
5 is a Odd Number
6 is a Even Number
24 is a Even Number
11 is a Odd Number

Related article


EmoticonEmoticon