Using a for loop, I want to check, if a certain condition is satisfied. Whenever this condition is satisfied, my program must execute a specific task. In addition, during the iteration proceeding the current one, a different specific task must be executed. Whenever the condition is not satisfied, nothing specific must happen.
I have come up with two approaches for this problem, but both of them feel like they are not a good practice. For an answer, I would like to know, why one (or both) of the methods can (or should not) be used, or an alternative solution.
Approach 1
In the following example, I simply want to know, if the number of the current iteration is divisible by 4. If it is, the program will print “divisible by 4” and set the boolean “flag” to true. Whenever the boolean “flag” is true, the program will print “flag true” and set it to false again. If my condition is not met, simply the number of the current iteration will be printed
func main() {
flag := false
for i := 1; i <= 10; i++ {
if i%4 == 0 {
fmt.Println(i, " divisible by 4")
flag = true
} else if flag {
fmt.Println(i, " flag true")
flag = false
} else {
fmt.Println(i)
}
}
}
This solution works perfectly fine, yet the scope of my “flag” variable is higher than required, as the variable is accessible by the entire function.
Output:
1
2
3
4 divisible by 4
5 flag true
6
7
8 divisible by 4
9 flag true
10
Approach 2
The example will be the same as in approach 1. Instead of using a flag variable and executing my specific task on the next iteration, I manually increment the value of my loop variable by 1, and execute both of my tasks sequentially.
func main() {
for i := 1; i <= 10; i++ {
if i%4 == 0 {
fmt.Println(i, " divisible by 4")
i++
fmt.Println(i, " print something")
} else {
fmt.Println(i)
}
}
}
Even though it works, I do not know if loop variables are ever supposed to be manipulated. An explanation, why this approach is valid / invalid would be very appreciated
Output:
1
2
3
4 divisible by 4
5 print something
6
7
8 divisible by 4
9 print something
10
1