1.

What is the syntax used for the for loop in Golang? Explain.

Answer»

Go language follows the below syntax for implementing for loop.

for [condition | ( init; condition; increment ) | Range] { statement(s); //more statements}

The for loop works as follows:

  • The init steps gets EXECUTED first. This is executed only once at the beginning of the loop. This is done for declaring and initializing the loop control variables. This FIELD is OPTIONAL as long as we have initialized the loop control variables before. If we are not doing ANYTHING here, the semicolon needs to be present.
  • The condition is then evaluated. If the condition is satisfied, the loop body is executed.
    • If the condition is not satisfied, the control flow goes to the next statement after the for loop.
    • If the condition is satisfied and the loop body is executed, then the control goes back to the increment statement which updated the loop control variables. The condition is evaluated again and the process repeats until the condition becomes false.
  • If the Range is mentioned, then the loop is executed for each item in that Range.

Consider an EXAMPLE for for loop. The following code prints numbers from 1 to 5.

package mainimport "fmt"func main() { // For loop to print numbers from 1 to 5 for j := 1; j <= 5; j++ { fmt.Println(j) }}

The output of this code is:

12345


Discussion

No Comment Found