Back to questions
JuniorTheoryCommon
What does the program print?
package main
import "fmt"
func main() {
s := 0
for i := 1; i < 5; i++ {
s += i
}
fmt.Println(s)
}10
- Expecting
15: the conditioni < 5is false onceireaches 5, so the body runs for 1, 2, 3 and 4 only. - Expecting the running sums
1 3 6 10:fmt.Printlnsits after the loop's closing brace, so it runs once, when the loop is over.
- How would you change the loop so that it adds 1 through 5?
- How would you write the same loop with only a condition after
for?