Go language-iteration

Iterative processing

I'm going to write the understanding of Go from the basics of programming!

Iterative processing

for i := 1; i <= 4; i ++ {  //Variable initialization;Repeating conditions;Variable update
  fmt.Println("Hello")
}

//console
Hello
Hello
Hello
Hello

1 is assigned to the variable i, and the processing in {} is repeated while "i is 4 or less" is satisfied. Variable update "i ++" is executed every time it finishes

Process flow

//Flow of iterative processing
❶ Initialization of variables
❷ Conditions
❸ Repeated processing
❹ Variable update
❷...
for i := 1; i <= 5; i ++ {  //❶i:=1;❷i<=5;❹i++
  fmt.Println(i)            //❸fmt.Println(i)
}

//console
1
2
3
4
5

Variable i is 1 in the first lap of repetition Every time the processing (③) in {} of for is completed, the variable i is updated (④) and changes to 1,2,3,4,5. And when i <= 5 (②) does not hold, the repetition ends automatically.

Repeat multiple processes

func main() {
  for i := 1; i <=3; i ++ {
    fmt.Println("Hello")
    fmt.Println(i)
  }
}

//console
Hello
1
Hello
2
Hello
3

If you write multiple processes in the {} of for, it will be repeated in the order in which they were written.

Notes on variable definition of for statement

for var i int =1; i <= 4; i ++ {  //Variable definition using var
  fmt.Println("Hello")
}

//console
Error that variable definition by var cannot be done with for statement

You cannot use var in the variable definition of the for statement You can only define variables using: =

Output numbers from 1 to 100 using iterative processing

package main

import "fmt"

func main() {
    for i := 1; i <= 100; i ++ {
        fmt.Println(i)
    }
}

Recommended Posts

Go language-iteration
Go language-address
Go Language-Functions
Go language-pointer
Go Language-Basic ❷
Python with Go
About Go functions
Go language-standard package
Go class basics
Go language-rand package
About Go Interface
use go module