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
+7.7k Javascript : Put image into Chrome browser's console
+12k Golang : Simple client-server HMAC authentication without SSL example
+8k Golang : Auto-generate reply email with text/template package
+13.3k Golang : Get user input until a command or receive a word to stop
+11.4k Golang : Fuzzy string search or approximate string matching example
+11.2k Golang : Concatenate (combine) buffer data example
+8.1k Golang : Oanda bot with Telegram and RSI example
+17.7k Golang : Get all upper case or lower case characters from string example
+28.5k Golang : Detect (OS) Operating System
+25k Golang : Storing cookies in http.CookieJar example
+21.9k Golang : Repeat a character by multiple of x factor
+4.7k Golang : Calculate a pip value and distance to target profit example