The classic first loop adds numbers up.
What to build
A program that adds the numbers from 1 to n.
Requirements
- Read n.
- Print
sum: Swith the sum of 1 to n, andeven sum: Ewith the sum of the even numbers from 1 to n.
Input
One whole number n.
Output
Two lines.
Constraints
1 ≤ n ≤ 10000.
Example
Input:
10
Output:
sum: 55
even sum: 30
Why it works
The loop visits every number from 1 to n. The if inside it adds only even numbers to the second total.
Examples
Example 1 · Input
10
Expected output
sum: 55 even sum: 30
Example 2 · Input
1
Expected output
sum: 1 even sum: 0
Hints
Hint 1
Use a counting loop from 1 to n and add i to the total.
Hint 2
Add i to the even total only when i % 2 == 0.
Solution
Show one correct solution (try it yourself first)
package main
import "fmt"
func main() {
var n int
fmt.Scan(&n)
sum, even := 0, 0
for i := 1; i <= n; i++ {
sum += i
if i%2 == 0 {
even += i
}
}
fmt.Println("sum:", sum)
fmt.Println("even sum:", even)
}