The for Loop
Go has just one loop keyword: for. There's no while or do-while; everything is written with for in different shapes.
The classic form has three parts separated by semicolons:
for i := 0; i < 5; i++ {
fmt.Println("Putaran ke-", i)
}
- Init
i := 0: runs once before the loop starts. - Condition
i < 5: checked before every iteration; if it'sfalse, the loop stops. - Post statement
i++: runs at the end of every iteration.
The variable i only lives inside the for block. Since Go 1.22, each iteration gets its own copy of i.
There are no parentheses around those three parts, but the curly braces { } are required.
Accumulating a value
A very common pattern: set up a variable outside the loop to hold the result, then update it on every iteration.
total := 0
for hari := 1; hari <= 7; hari++ {
total += hari * 1000
}
fmt.Println(total) // 28000
Task
In an RPG, going from level i-1 to level i takes i * 100 XP. So reaching level 1 takes 100 XP, level 2 takes 200 XP, and so on.
Complete the following two functions using the classic for loop:
func totalXP(level int) int: the total XP needed to go from level 0 up tolevel, that is100 + 200 + ... + level*100. Forlevel <= 0, the result is0.func bonusBeruntun(hari int) int: a daily login bonus. The first day gives 10 coins, and each following day's bonus is double the previous day's. Return the total coins afterhari(days) of consecutive logins (hari <= 0→0).
Example: totalXP(3) = 600, bonusBeruntun(3) = 10 + 20 + 40 = 70.