Omitting Conditions from a for Loop in Go

Loops in Go can omit sections of a for loop. For example, the CONDITION (middle part) can be omitted which causes the loop to run forever.

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

Assignment

Complete the maxMessages function. Given a cost threshold, it should calculate the maximum number of messages that can be sent.

Each message costs 100 pennies, plus an additional fee. The fee structure is:

  • 1st message: 100 + 0

  • 2nd message: 100 + 1

  • 3rd message: 100 + 2

  • 4th message: 100 + 3

Solution

solution.go
package main

func maxMessages(thresh int) int {
	totalCost := 0

	for messageCount := 0; ; messageCount++ {
		addition := 100 + messageCount
		if totalCost+addition > thresh {
			return messageCount
		} else {
			totalCost += addition
		}

	}

}

Why It Works

1

Infinite Loop with Omitted Condition

  • Initial: messageCount := 0 - starts counting from 0

  • Condition: ; (empty) - the loop runs forever

  • After: messageCount++ - increments after each iteration

  • The empty middle section is the key concept from this lesson

2

Calculate Next Message Cost

  • Every message has a base cost of 100 pennies

  • Plus an incremental fee equal to messageCount

  • Example: message 0 costs 100, message 1 costs 101, message 2 costs 102

3

Check BEFORE Adding

  • Critical: Check if adding the next message would exceed the threshold

  • We check totalCost + addition, not just totalCost

  • This is a "look-ahead" check - can we afford this next message?

  • If we can't afford it, return the current count (we don't send this message)

4

Add Cost and Continue

  • If we can afford the message, add its cost to our running total

  • The loop continues to the next iteration (no return)

  • messageCount++ happens automatically due to the for loop's AFTER section

Key Insights

  • Why > and not >=? We want to send messages up to and including the threshold, not stop before it

  • Why check before adding? If we add first and check after, we're always one message behind

  • Why omit the condition? We don't know how many iterations we need - we return dynamically when we hit the limit

  • No break needed: We use return to exit the infinite loop when the condition is met

Example Walkthrough

For thresh = 205:

Iteration
messageCount
addition
totalCost before
totalCost + addition
Action

1

0

100

0

100

100 ≀ 205, add it (totalCost = 100)

2

1

101

100

201

201 ≀ 205, add it (totalCost = 201)

3

2

102

201

303

303 > 205, return 2

Result: 2 messages can be sent