read input argument numbers and print the sum in go

To read input argument numbers and print their sum in Go, we need to use the os package to access the command-line arguments. Here's an example program:

main.go
package main

import (
	"fmt"
	"os"
	"strconv"
)

func main() {
	sum := 0
	for _, arg := range os.Args[1:] {
		num, err := strconv.Atoi(arg)
		if err != nil {
			fmt.Printf("%s is not a valid number\n", arg)
			continue
		}
		sum += num
	}
	fmt.Printf("Sum: %d\n", sum)
}
272 chars
21 lines

In this program, we use a for loop to iterate over the command-line arguments starting from the second argument (os.Args[1:]). For each argument, we use the strconv.Atoi() function to convert it to an integer. If the conversion fails (i.e., the argument is not a valid number), we print an error message and continue to the next argument.

Otherwise, we add the number to a running total called sum. Finally, we print the sum using fmt.Printf().

To run this program, we can pass any number of space-separated integers as command-line arguments:

main.go
$ go run sum.go 1 2 3
Sum: 6
29 chars
3 lines

If any of the arguments are not valid numbers, they will be skipped with an error message:

main.go
$ go run sum.go 1 2 foo 3 bar
foo is not a valid number
bar is not a valid number
Sum: 6
89 chars
5 lines

related categories

gistlibby LogSnag