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:
- They add
setoran(the deposit) to the balance. - 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, return0. - If
setoran <= 0and 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):
| Month | After deposit | Interest | Ending balance |
|---|---|---|---|
| 1 | 1000 | 10 | 1010 |
| 2 | 2010 | 20 | 2030 |
| 3 | 3030 | 30 | 3060 |
The result is 3.