Loops in Go
# CHAPTER 8
Loops in Go
1. Introduction
Imagine you need to insert 5,000 user records into a database. Writing the insert command 5,000 times manually is impossible. Loops solve this by allowing a block of code to execute repeatedly as long as a condition is true.In C, Java, and Python, you have for, while, and do-while loops.
Go has only one looping keyword: for.
The Go creators designed for to be so flexible that it can replicate all the others, keeping the language simple.
2. Learning Objectives
By the end of this chapter, you will be able to:-
Use the standard
forloop (Initialization, Condition, Post).
-
Use the
forloop as awhileloop.
- Create Infinite loops.
-
Manipulate execution flow using
breakandcontinue.
-
Understand the basics of the
rangekeyword.
3. The Standard for Loop
Used when you know exactly how many times you want the loop to run.
Syntax: for initialization; condition; post { // code }
How it works:
-
1.
i := 1(Initialization): Executes ONCE at the start.
-
2.
i <= 5(Condition): Checked before every loop. If true, run the code. If false, stop.
-
3.
i++(Post): Executes *after* the code block runs, then goes back to step 2.
4. The "While" Loop (Using for)
If you drop the Initialization and Post statements, the for loop behaves exactly like a traditional while loop. Used when you don't know the exact number of iterations, but you know the stopping condition.
5. The Infinite Loop
If you drop all three components, the loop will run forever. This is heavily used in backend web servers that must run 24/7 to listen for incoming requests.
6. Flow Control: break and continue
-
break: Immediately stops and destroys the loop completely.
-
continue: Skips the rest of the *current* iteration and instantly jumps back to the top for the next iteration.
7. The range Keyword (Preview)
We will cover Arrays and Maps later, but the most common way to loop over collections of data in Go is using the for ... range syntax.
8. Mini Project: Multiplication Table Generator
Let's build a program that generates a math table using loops.9. Common Mistakes
-
Infinite Loops by Accident: Forgetting to include
count++in a while-style loop. The condition never becomes false, freezing the program and maxing out a CPU core.
-
Off-by-One Errors: Using
< 5instead of<= 5when you actually want the loop to run exactly 5 times starting from 1.
10. Best Practices
-
Keep Loops Small: If the code inside your
forloop is 100 lines long, extract it into a separate Function. Loops should be clean and easy to read.
11. Exercises
-
1.
Write a
forloop that prints all even numbers from 2 to 20.
-
2.
Write a while-style
forloop that creates a countdown timer from 10 to 1, then prints "Liftoff!".
12. MCQs with Answers & Explanations
How many different loop keywords does Go have?
Which part of a standard for loop executes ONLY ONCE at the very beginning?
How do you write a while loop in Go?
How do you create an infinite loop in Go?
What does the break statement do?
What does the continue statement do?
What causes an accidental infinite loop?
What keyword is heavily used in Go to loop over arrays, slices, and maps automatically?
What is the output of for i := 0; i < 3; i++ { fmt.Print(i) }?
for loop inside another for loop?
a) Yes, this is called a nested loop b) No, the compiler prevents it
Answer: a) Yes, this is called a nested loop.
13. Interview Preparation
Interview Questions:-
1.
Why did the creators of Go decide to exclude the
whilekeyword from the language? (Answer: Minimalism.forcan replicatewhileperfectly, making the language smaller and easier to read).
-
2.
What happens if you run an infinite loop
for {}on a backend server without any blocking code (like listening for network requests)? (Answer: It will consume 100% of a CPU core instantly).
14. Summary
Automation is the core of programming. Go provides a single, highly flexible loop keyword:for. It can act as a standard counter, a conditional while loop, or run infinitely. Control keywords like break and continue give you fine-grained control over execution flow.
15. Next Chapter Recommendation
Up until now, we've written all our code straight down insidemain(). As programs grow, this becomes unreadable. In Chapter 9: Functions in Go, we will learn how to break our code into small, reusable, organized blocks.