Basic Loop Concept
Imagine you need to print “Hello World!” three times. Writing the print statement three times is inefficient compared to using a loop. A counter variable (commonly named i) can track iterations, and a for loop can repeatedly execute your print statement. Consider this process:- Initialize i with 1.
- Check if i is between 1 and 3 (inclusive).
- If the condition is true, print “Hello World!”.
- Increment i by 1.
- Repeat steps 2–4 until the condition fails.
For Loop Syntax
The general syntax for a for loop in Go is:- Initialization Statement (Optional): Executed once before the loop starts. It typically declares and assigns a starting value.
- Condition Statement: A Boolean expression evaluated before each iteration. If it evaluates to true, the loop body executes; if false, the loop exits.
- Post Statement (Optional): Executed at the end of each iteration. This is often used to update the counter variable.
Example: Printing Squares of Numbers
Let’s create a Go program that prints the square of numbers from 1 to 5. There are two common approaches.Full For Loop Syntax
This version uses the complete for loop header:Simplified Loop with External Initialization
Alternatively, you can initialize the variable outside the loop and include only the condition in the header:Infinite Loops
A for loop in Go becomes an infinite loop if both the initialization and post statements are omitted, and the condition is not specified. Consider this example:Infinite loops can cause your program to run endlessly, which may lead to resource exhaustion. Always ensure there’s a proper exit condition.
Controlling Loop Execution: break and continue
In certain situations, you may want to exit the loop prematurely or skip specific iterations. Thebreak and continue statements are useful tools for such scenarios.
Using break
Thebreak statement immediately terminates the loop when a particular condition is met. In the program below, the loop stops processing when i equals 3:
Using continue
If you want to skip the current iteration and proceed with the next one, use thecontinue statement. The example below bypasses printing the value when i equals 3:
The
continue statement allows your loop to skip over specific iterations without exiting the entire loop, providing greater control over loop execution.That concludes our detailed tutorial on using for loops in Go programming. For more hands-on practice, consider exploring additional lab exercises and examples available in our documentation.