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
+4.4k MariaDB/MySQL : How to get version information
+11.3k Golang : Simple file scaning and remove virus example
+12.3k Android Studio : Highlight ImageButton when pressed on example
+9.2k Golang : Scramble and unscramble text message by randomly replacing words
+5.2k Python : Delay with time.sleep() function example
+26.5k Golang : Force your program to run with root permissions
+16.7k Golang : Get input from keyboard
+7.1k Golang : Individual and total number of words counter example
+11.9k Golang : convert(cast) string to integer value
+7.5k Golang : Lock executable to a specific machine with unique hash of the machine
+9.1k Golang : How to protect your source code from client, hosting company or hacker?
+37.7k Golang : Read a text file and replace certain words