Go course

LoopsThe for Loop

Go

Display

Theme

Loops · Test exercise

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)
}
  1. Init i := 0: runs once before the loop starts.
  2. Condition i < 5: checked before every iteration; if it's false, the loop stops.
  3. 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:

  1. func totalXP(level int) int: the total XP needed to go from level 0 up to level, that is 100 + 200 + ... + level*100. For level <= 0, the result is 0.
  2. 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 after hari (days) of consecutive logins (hari <= 0 → 0).

Example: totalXP(3) = 600, bonusBeruntun(3) = 10 + 20 + 40 = 70.

main.go
package main

import "fmt"

func totalXP(level int) int {
	// TODO: jumlahkan i*100 untuk i dari 1 sampai level
	return 0
}

func bonusBeruntun(hari int) int {
	// TODO: 10, 20, 40, ... jumlahkan sebanyak hari
	return 0
}

func main() {
	fmt.Println("XP sampai level 5:", totalXP(5))
	fmt.Println("Bonus 7 hari:", bonusBeruntun(7))
}

Output

Go runtime not loaded yet

Press Run to see the output, or Submit to check your code.

Ctrl/Cmd + Enter: Run · Ctrl/Cmd + Shift + Enter: Submit · Ctrl/Cmd + S: tidy the code (gofmt)