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
+8.4k Golang : Accessing content anonymously with Tor
+4.8k nginx : force all pages to be SSL
+7k Golang : Add build version and other information in executables
+5.2k Golang : Detect face in uploaded photo like GPlus
+25.7k Golang : Find files by name - cross platform example
+6.9k Golang : Configure Apache and NGINX to access your Go service example
+6.1k Golang : Accessing dataframe-go element by row, column and name example
+4.8k Get website traffic ranking with Similar Web or Alexa
+11k Golang : Encrypt and decrypt data with x509 crypto
+6.9k Golang : Load DSA public key from file example
+28.6k Golang : How to get HTTP request header information?
+17.2k Golang : Read binary file into memory