In programming, a loop is used to repeat a block of code. For example,
If we want to print a statement 100 times, instead of writing the same print statement 100 times, we can use a loop to execute the same code 100 times.
This is just a simple example; we use for loops to clean and simplify complex programs.
In Golang, we use the for loop to repeat a block of code until the specified condition is met.
Here's the syntax of the for loop in Golang.
Here,
true, the body of the for loop is executed.false.false, the for loop ends.
Output
Here is how this program works.
| Iteration | Variable | Condition: i | Action |
|---|---|---|---|
| 1st | i = 1 | true | 1 is printed. i is increased to 2 |
| 2nd | i = 2 | true | 2 is printed. i is increased to 3 |
| 3rd | i = 3 | true | 3 is printed. i is increased to 4 |
| 4th | i = 4 | true | 4 is printed. i is increased to 5 |
| 5th | i = 5 | true | 5 is printed. i is increased to 6 |
| 6th | i = 6 | false | The loop is terminated. |
Output
Here, we have used a for loop to iterate from i equal to 1 to 10.
In each iteration of the loop, we have added the value of i to the sum variable.