Golang : Test a slice of integers for odd and even numbers
Got this question from one of my students and he is from a disadvantaged background(he is a refugee). He wanted to know how to accept a line of integers and test each of the numbers to see if they are odd or even. Below is a simple program that can do just that.
NOTE: Sometimes things that we take for granted can be so exciting and fascinating for those that don't have this "luxury" in their life. Luxury such as able to touch a computer, go online and learn to program in a safe environment.
package main
import (
"bufio"
"fmt"
"os"
"strconv"
"strings"
)
func main() {
fmt.Print("Enter a number to test if odd or even : ")
//fmt.Scanf("%d", &num)
numberReader := bufio.NewReader(os.Stdin)
num, _ := numberReader.ReadString('\n')
// the input can be multiple integers with spaces in between
// turn to slice
numSlice := strings.Fields(num)
for _, v := range numSlice {
i, _ := strconv.Atoi(v)
if i%2 == 0 {
fmt.Println(v, "is Even")
} else {
fmt.Println(v, "is Odd")
}
}
}
Sample input and output:
$ go run oddeven.go
Enter a number to test if odd or even : 1 2 3 4 5 6 7 8 9
1 is Odd
2 is Even
3 is Odd
4 is Even
5 is Odd
6 is Even
7 is Odd
8 is Even
9 is Odd
$ go run oddeven.go
Enter a number to test if odd or even : 99 98 97 96 55 33 1
99 is Odd
98 is Even
97 is Odd
96 is Even
55 is Odd
33 is Odd
1 is Odd
May you learn enough from me to have a better life :-)
See also : Golang : Number guessing game with user input verification example
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+18.8k nginx: [emerg] unknown directive "passenger_enabled"
+4.6k Unix/Linux : How to find out the hard disk size?
+5.5k Android Studio : Hello World example
+5.6k Golang : How to setup a disk space used monitoring service with Telegram bot
+7.8k Golang : Capture text return from exec function example
+8.4k Facebook : Getting the friends list with PHP return JSON format
+11.6k Golang : Convert int(year) to time.Time type
+15.1k Golang : Test floating point numbers not-a-number and infinite example
+4.8k Unix/Linux : How to test user agents blocked successfully ?
+6.5k Golang : Convert source code to assembly language
+4.4k Golang : If else example and common mistake
+5.1k PageSpeed : Clear or flush cache on web server