I provided you with a link to a Go for loop explanation with this example:
package main
import "fmt"
func main() {
sum := 0
for i := 0; i < 10; i++ {
sum += i
}
fmt.Println(sum)
}
The example is close to what you want: it’s the sum of the numbers from 0 to 9. You want the sum of the numbers from 20 to 100. What changes to the example will give you the answer that you want?
I don’t understand what you are asking. It doesn’t seem relevant to your exercise.
Go does not have a Python-like range sequence type.
I can clearly solve that in a for loop as well. The problem is that I do not understand why 20 -> 2; 21 -> 3. Or how to use that when summing 20 + 21 + 22 + 23 + … + 100…
Printing the sum of all digits in the variable “a” in a for loop. So, assuming the initial value of the variable “a” equal to 20 and the upper bound of 100, I expect this output:
20 -> 2
21 -> 3
22 -> 4
23 -> 5
24 -> 6
25 -> 7
26 -> 8
27 -> 9
28 -> 10
29 -> 11
30 -> 3
31 -> 4
…
99 -> 18
100 -> 1
I did as in the answer, but I don’t know how to get these values, for example I marked “?” In the code below.
package main
import “fmt”
func main () {
sum: = 0
for a: = 20; a <101; a ++ {
sum + = a
fmt.Println (a, “->” “?”)
package main
import "fmt"
func sumDigits(a int) int {
if a < 0 {
a = -a
}
sum := 0
for a > 0 {
sum += a % 10
a = a / 10
}
return sum
}
func printSums(lo, hi int) {
for a := lo; a <= hi; a++ {
fmt.Println(a, "->", sumDigits(a))
}
}
func main() {
printSums(20, 100)
}