In the previous section, you learned how to perform certain actions based on specific conditions, right? One concept that is frequently used alongside conditional statements in programming is the "loop." A "loop" means performing a specific task repeatedly as long as a certain condition is met.
For example, if we need to print the '*' character 100 times on the screen, how should we do it? If we use the method we learned earlier, we would probably have to write the code as shown in [Code 1].
In the above example, you would need to copy and paste the fmt.Println() function 100 times or type it in manually. But if the number of repetitions were 1,000 or 10,000, it would be too difficult to write the code one by one and count the occurrences. To make this task easier, Go provides a loop called 'for' that helps you repeat actions efficiently.
for statement flow
Initialization: The initialization is the code executed before the 'for' loop starts. It is used to initialize the variables that are used in the condition expression of the 'for' loop.
Condition: The condition specifies the judgment criteria for executing the block of the 'for' loop (code 1, ..., code N). If the condition is true, the block inside the condition will be executed. If the condition is false, the loop will exit the block.
Final Expression After Block: This is the code executed at the end of the condition block. It is typically used to modify the condition expression to eventually make it false.
In the above structure, the block of code that is executed when the 'for' loop is true is called the "for loop." The dictionary meaning of 'loop' is 'ring,' and in this context, it means that the block of statements executed when the 'for' loop's condition is satisfied is connected like a ring, continuously repeating.
When [Code 1] is written using 'for', it becomes the same format as [Code 2].
package main
import "fmt"
func main() {
for i := 1; i <= 5; i++ {
fmt.Println("*")
}
// The same format as the above code
j := 1
for j <= 5 {
fmt.Println("*")
j++
}
}
[Code 2] for loop
Lines 06 to 08 of [Code 2] initialize the integer variable i to 1, and then the loop repeats as long as i is less than or equal to 5. After executing the fmt.Println() function, the value of i is increased by 1 (i++) within the 'for' loop. In other words, the fmt.Println() function is executed once for each iteration, and the loop will terminate when the value of i becomes 6
Structure of for loop
Just like in lines 12 to 16, the 'initialization' of the 'for' loop can be structured before the 'for' loop, and the 'final expression after block' can be placed at the very end of the block to achieve the same effect.
In the previous chapter, while learning about conditional statements, we observed that another conditional statement can be placed inside the block of a condition. Similarly, a 'for' loop can be nested inside another 'for' loop. Let's write [Code 3] to verify this:
package main
import "fmt"
func main() {
for i := 2; i <= 9; i++ { // Outer loop for the first multiplier
for j := 1; j <= 9; j++ { // Inner loop for the second multiplier
fmt.Printf("%d * %d = %d\n", i, j, i*j)
}
}
}
[Code 3] Print the multiplication table using nested for loops
This code will print the multiplication table using nested for loops
2 * 1 = 2
2 * 2 = 4
...
9 * 8 = 72
9 * 9 = 81
Changes in the variable values of nested loops
In [Code 3], the value of i increases from 2 to 9, performing the 'outer loop' each time, and inside the loop, the value of j increases from 1 to 9 while executing the fmt.Printf() function. In other words, to implement the multiplication table from 2 to 9 in the program, the 'i' variable was first assigned to represent each step, and for each variable, a 'j' variable was created to perform the multiplication from 1 to 9. By using nested loops, you can simplify complex code and make the process more efficient.
Utilizing Branching: break, continue
In the previous section, we learned that when the condition is not satisfied, we exit the loop(block). However, while programming, there are cases where we need to exit the loop in the middle under specific conditions. In such cases, we use the 'break' statement and the 'continue' statement.
1) Usage of break
The dictionary meaning of 'break' is to stop, right? If you think of a car brake, it will be easy to understand. When the 'break' statement is encountered during the execution of a loop, it stops the execution within the block and exits the block. Let's look at an example in [Code 4].
package main
import "fmt"
func main() {
for {
fmt.Println("loop")
break
}
fmt.Println("Exit Loop")
}
[Code 4] exit when meet break
In [Code 4], you can see that the condition part of the 'for' loop is missing, right? In the case of a loop without a condition, there is no condition to stop the loop, so it will result in an infinite loop. If line 07 is removed, the word 'loop' will continue to be printed on the screen. While programming, there may be situations where you need to exit the block even if the condition is not satisfied. In such cases, when 'break' is encountered, it will immediately exit the loop.
2) Usage of continue
The dictionary meaning of 'continue' is "to keep going (without stopping)." When 'continue' is encountered inside a block, it skips the remaining code below it and goes back to the beginning of the loop. Let's write [Code 5].
package main
import "fmt"
func main() {
for i := 1; i <= 10; i++ {
if i%2 == 0 {
continue
}
fmt.Println(i)
}
}
[Code 5] Usage of Continue
Looking at line 06, when the remainder of the value of 'i' divided by 2 is 0, the 'continue' statement is encountered, causing the loop to jump to the beginning. As a result, even numbers are not printed, and only odd numbers (those with a remainder of 1 when divided by 2) are printed.
In this chapter, we learned how to construct loops to simplify repetitive tasks, and we explored how to exit a loop using branching commands instead of conditionals. Since conditional statements and loops are the most important parts of a program, I hope you thoroughly understand them before moving on.