|
1 | 1 | # Introduction |
2 | 2 |
|
| 3 | + |
3 | 4 | ## General syntax |
4 | 5 |
|
5 | | -The for loop is one of the most commonly used statements to repeatedly execute some logic. In Go it consists of the `for` keyword, a header and a code block that contains the body of the loop wrapped in curly brackets. The header consists of 3 components separated by semicolons `;`: initilization, condition and step. |
| 6 | +The for loop is one of the most commonly used statements to repeatedly execute some logic. In Go it consists of the `for` keyword, a header and a code block that contains the body of the loop wrapped in curly brackets. The header consists of 3 components separated by semicolons `;`: init, condition and post. |
6 | 7 |
|
7 | 8 | ```go |
8 | | -for initialization; condition; step { |
| 9 | +for init; condition; post { |
9 | 10 | // loop body - code that is executed repeatedly as long as the condition is true |
10 | 11 | } |
11 | 12 | ``` |
12 | 13 |
|
13 | | -- The **initialization** component is some code that runs only once before the loop starts. |
| 14 | +- The **init** component is some code that runs only once before the loop starts. |
14 | 15 | - The **condition** component must be some expression that evaluates to a boolean and controls when the loop should stop. The code inside the loop will run as long as this condition evaluates to true. As soon as this expression evaluates to false, no more iterations of the loop will run. |
15 | | -- The **step** component is some code that will run at the end of each iteration. |
| 16 | +- The **post** component is some code that will run at the end of each iteration. |
16 | 17 |
|
17 | 18 | **Note:** Unlike other languages, there are no parentheses `()` surrounding the three components of the header. In fact, inserting such parenthesis is a compilation error. However, the braces `{ }` surrounding the loop body are always required. |
18 | 19 |
|
19 | 20 | ## For Loops - An example |
20 | 21 |
|
21 | | -The initialization component usually sets up a counter variable, the condition checks whether the loop should be continued or stopped and the step increments the counter at the end of each repetition. |
| 22 | +The init component usually sets up a counter variable, the condition checks whether the loop should be continued or stopped and the post component usually increments the counter at the end of each repetition. |
22 | 23 |
|
23 | 24 | ```go |
24 | 25 | for i := 1; i < 10; i++ { |
25 | 26 | fmt.Println(i) |
26 | 27 | } |
27 | 28 | ``` |
28 | 29 |
|
29 | | -This loop will print the numbers from `1` to `9` inclusivé. |
| 30 | +This loop will print the numbers from `1` to `9` (including `9`). |
30 | 31 | Defining the step is often done using an increment or decrement statement, as shown in the example above. |
0 commit comments