Go course

Loopsfor as while

Go

Display

Theme

Loops · Test exercise

for as while

You can leave out the init and post statement of a for. If only the condition is left, for behaves like while in other languages:

energi := 100
for energi > 0 {
	energi -= 30
	fmt.Println("Sisa energi:", energi)
}

The loop keeps going as long as its condition is true. This form fits when you don't know up front how many times the loop should run; you only know when it should stop.

Make sure something inside the loop changes the condition. Otherwise the loop never stops (an infinite loop).

Task

A barista is saving up to buy an espresso machine. Every month:

  1. They add setoran (the deposit) to the balance.
  2. Then the bank pays 1% interest on the current balance (integer division: saldo / 100), which is added to the balance.

Complete func bulanSampaiTarget(saldo, setoran, target int) int, which returns how many months it takes until saldo >= target, using a while-style for.

  • If the starting balance is already >= target, return 0.
  • If setoran <= 0 and the starting balance hasn't reached the target, return -1 (the target will never be reached, so don't let the loop spin forever!).

Example: bulanSampaiTarget(0, 1000, 2500):

MonthAfter depositInterestEnding balance
11000101010
22010202030
33030303060

The result is 3.

main.go
package main

import "fmt"

func bulanSampaiTarget(saldo, setoran, target int) int {
	// TODO: gunakan for dengan kondisi saja (gaya while)
	return 0
}

func main() {
	fmt.Println("Butuh", bulanSampaiTarget(500000, 750000, 8000000), "bulan")
}

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)