Control Flow - Loops
Master the only loop construct in Go: the versatile for loop
Learning Objectives
- Use the standard three-component for loop
- Implement while-style loops using for
- Create infinite loops
- Use break and continue to control loop flow
- Introduction to the range keyword
The One and Only: for Loop
In many languages, you have for, while, and do-while loops. Go takes a simpler approach: it only has the for loop. However, this single construct is versatile enough to handle all looping needs.
Standard Three-Component Loop
The most common form is similar to C or Java:
|
|
- Init statement: executed before the first iteration (usually
i := 0) - Condition expression: evaluated before every iteration. If false, the loop stops.
- Post statement: executed at the end of every iteration (usually
i++)
if, the for loop does not use parentheses around its components, but braces {} are required.for as a “while” Loop
If you omit the init and post statements, the for loop behaves like a while loop:
|
|
Infinite Loops
If you omit the condition as well, you get an infinite loop:
|
|
Loop Control: break and continue
break: Immediately exits the loop.continue: Skips the rest of the current iteration and starts the next one.
|
|
Iterating with range
The range keyword is used to iterate over elements in a variety of data structures (arrays, slices, maps, strings, and channels). We’ll cover these structures in detail later, but here’s a sneak peek with a string:
|
|
Nested Loops
You can put loops inside loops:
|
|
Labelled break and continue
When dealing with nested loops, you can use labels to break or continue an outer loop:
|
|
Summary
Today you learned:
- Go only has one loop keyword:
for - The three forms of
for: standard, while-style, and infinite - How to use
breakandcontinue - How to use
rangefor basic iteration - Using labels to control nested loops
Practice Exercise
- Write a program that prints the multiplication table for a given number (1 to 10).
- Write a program that finds all prime numbers between 1 and 50 using nested loops.
- Use a
forloop to reverse a string (Hint: iterate backwards or userange). - Implement a “Guess the Number” game where the user has limited attempts to guess a number, using
forandbreak.
Next Steps
Tomorrow, we’ll dive into Functions - the building blocks of Go programs!
Now, test your loop knowledge with the quiz!
Quiz
Complete this quiz with a minimum score of 80% to mark Day 5 as complete.
Discussion
Have questions or want to discuss this lesson? Join the conversation below!