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
+22.6k Golang : Calculate time different
+5.4k Unix/Linux : How to find out the hard disk size?
+8k Golang : Oanda bot with Telegram and RSI example
+42.6k Golang : Convert []byte to image
+9.4k Golang : Eroding and dilating image with OpenCV example
+12.6k Golang : Convert int(year) to time.Time type
+13.7k Golang : Compress and decompress file with compress/flate example
+8.9k nginx: [emerg] bind() to 0.0.0.0:80 failed (98: Address already in use)
+12.3k Golang : HTTP response JSON encoded data
+13.7k Golang: Pad right or print ending(suffix) zero or spaces in fmt.Printf example
+6.5k Golang : Derive cryptographic key from passwords with Argon2
+25.1k Golang : Daemonizing a simple web server process example