I was wondering if someone could explain me the meaning of the accumulator in this code cause I can’t understand the output! here’s the code when I scan 3 as “n” :
package main
import “fmt”
func main() {
var n int
fmt.Scan(&n)
accumulator := 1
for i := 1; i <= n; i++ {
switch {
case i < 5:
accumulator *= i
case i < 10:
accumulator += i
}
}
fmt.Println("Accumulator=", accumulator)
}
output: 6
I think that there’s something I don’t know about the accumulator
but why 59? if any n greater than or equal to 9 won’t change anything from the output, I have to do: 1+2+3+4+5+6+7+8+9 + accumulator but this doesn’t show me 59
For functions like this, I think the Print function “family” in the fmt package is extremely useful. I added some calls to fmt.Printf and fmt.Println to your code just to print out what’s going on and I think it makes it easier to understand what’s happening and why:
I would also add that reviewing code I would take the time to say the following with each statement.
accumulator := 1
We are creating a variable of TYPE INT using the short declaration operator. I know this is obvious but being explicit about each statement will help understand what this accumulator actually does.
Within the for loop we handle some conditional logic such that when i, which is 1 entering the for loop, encounters the first case statement it checks if it is less than 5. It is therefore it will get multiplied by 1 and then assigned back into the accumulator variable. The second case will also be hit because i is less than 10 therefore we add 1 to the accumulator, etc…
I would also recommend you using delve to step through your code as debugging is a great way to learn what is actually going on.