The simplest input program reads a count and then that many numbers.
What to build
A program that adds up a list of numbers.
Requirements
- Read n, then n whole numbers.
- Print their sum.
Input
Line 1: n. Then n whole numbers, on one or more lines.
Output
One number.
Constraints
1 ≤ n ≤ 1000; each number is between -1000 and 1000.
Example
Input:
3
1 2 3
Output:
6
Why it works
fmt.Scan reads across spaces and lines, so it does not matter how the numbers are split into lines. The running total starts at 0 and grows with each number.
Examples
Example 1 · Input
3 1 2 3
Expected output
6
Example 2 · Input
5 10 -4 7 8 -1
Expected output
20
Hints
Hint 1
Read n first, then repeat n times: read x and add it to a total.
Hint 2
Start the total at 0.
Solution
Show one correct solution (try it yourself first)
package main
import "fmt"
func main() {
var n int
fmt.Scan(&n)
sum := 0
for i := 0; i < n; i++ {
var x int
fmt.Scan(&x)
sum += x
}
fmt.Println(sum)
}