Loops in Go

The basic loop in Go is written in standard C-like syntax:

for INITIAL; CONDITION; AFTER{
  // do something
}

INITIAL is run once at the beginning of the loop and can create variables within the scope of the loop.

CONDITION is checked before each iteration. If the condition doesn't pass then the loop breaks.

AFTER is run after each iteration.

For example:

for i := 0; i < 10; i++ {
  fmt.Println(i)
}
// Prints 0 through 9

Assignment

At Textio we have a dynamic formula for determining how much a batch of bulk messages costs to send. Complete the bulkSend() function.

It should return the total cost (as a float64) to send a batch of numMessages messages. Each message costs 1.0, plus an additional fee. The fee structure is:

  • 1st message: 1.0 + 0.00

  • 2nd message: 1.0 + 0.01

  • 3rd message: 1.0 + 0.02

  • 4th message: 1.0 + 0.03

  • ...

Use a loop to calculate the total cost and return it.

Solution

1

Step 1

total := 0.0 β€” Start with zero total cost

2

Step 2

for i := 0; i < numMessages; i++ β€” Loop from 0 up to numMessages - 1

3

Step 3

fee := 0.01 * float64(i) β€” Fee grows each message (0.00, 0.01, 0.02, …)

4

Step 4

cost := 1.0 + fee β€” Each message costs $1 plus the fee

5

Step 5

total += cost β€” Add that cost to the running total

6

Step 6

return total β€” Return total cost after the loop

Example

Summary for Obsidian Notes

Go for loop structure

Example pattern

Key ideas

  • Use a variable (like total) to keep a running sum.

  • Don’t return inside the loop unless you mean to stop early.

  • Convert integers to floats when doing decimal math: float64(i).

Second Solution

How to increment fee properly

Explanation

Line
What it does

fee := 0.0

Start fee at zero

for i := 0; i < numMessages; i++

Loop once for each message

cost := 1.0 + fee

Base cost plus the current fee

total += cost

Add this cost to the total

fee += 0.01

Increase fee by 0.01 for next iteration

Example

Each loop:

Message 1 β†’ fee=0.00 β†’ cost=1.00 Message 2 β†’ fee=0.01 β†’ cost=1.01 Message 3 β†’ fee=0.02 β†’ cost=1.02 Total = 3.03

Key Takeaway

Your logic was right β€” you just needed to:

  • Initialize fee before the loop,

  • Increment it inside the loop body (not in the for header).

Last updated