# [basics of GO language] VI. loop control statement, process control and programming practice (for, break, continue, goto)

As a beginner of network security, you will encounter malicious samples developed in Go language. Therefore, starting from today to explain the Golang programming language from zero, on the one hand, it is to urge yourself to move forward and learn new knowledge; The other is to share with readers and hope everyone can make progress together. The previous article introduced Golang's sequence control statements and conditional control statements. This article will explain loop control statements and process control in detail, including for, break, continue, goto and related programming exercises.

The introductory part of this series of articles will refer to the video and book GO advanced programming by Mr. Han Shunping of "Shang Silicon Valley". See the references for details, and learn and enrich it in combination with the author's many years of programming experience. Watch and cherish it! In the follow-up, we will conduct GO language practice in combination with network security. Come on~

Over the years, I have learned various programming languages, from the earliest C language to C + +, to c#, PHP, JAVA, to IOS development, Python, to the latest GO language. It is really miscellaneous. Sometimes I think programming language is just the simplest, and its value lies in solving practical problems or going deep into the bottom through a programming language. When we learn a programming language well, other programming languages are very similar, the same way, and learn very quickly. • https://github.com/eastmountyxz/Go-learning

Previous reference:

### Article directory:

• 1, for loop control 1. Basic grammar 2. For range cycle 3. Classic case of for programming 4. Similar to while and do while loops
• 2, Multiple cycle control Case 1: Round Robin average Case 2: circular printing of pyramids and inverted triangles
• 3, Jump control statement 1.break 2.continue
• 4, goto statement
• 5, Jump control statement return
• 6, Golang programming exercise

# 1, for loop control

## 1. Basic grammar

Syntax format of for loop:

```for Loop variable initialization; Cycle condition; Cyclic variable iteration {
Loop operation statement
}
```

The for loop has four main elements, including:

• Loop variable initialization
• Cycle condition
• Loop operation (statement), also known as loop body
• Cyclic variable iteration

The basic flow of the for loop statement is as follows: The execution sequence of the for loop is described as follows:

• Perform loop variable initialization, such as N: = 1
• Execute loop conditions, such as n < = 10
• If the loop condition is true, the loop operation is performed
• Perform a loop variable iteration, such as i++
• Repeat the above three steps until the loop condition is False, and then exit the for loop

Here is a simple example:

```package main
import "fmt"

func main() {
//for loop
for n := 1; n <= 10; n++ {
fmt.Println("Eastmount", n)
}
}
```

The output results are shown in the figure below: The second syntax format of for: The for loop condition is an expression that returns a Boolean value. The second way is to write variable initialization and variable iteration to other locations.

```for Cyclic judgment condition {
//Loop execution statement
}
```

The case is as follows: The third syntax format for: The following expression is equivalent to for; {}, which is an infinite loop and usually needs to be used with break statements.

```for {
//Loop execution statement
}
```

The case is as follows: ## 2. For range cycle

The range keyword in the Go language is used to iterate over the elements of an array, slice, channel, or set (map) in a for loop. In the array and slice, it returns the index of the element and the value corresponding to the index, and returns the key value pair in the collection. Array is introduced in subsequent articles. Here we mainly introduce traversal strings.

• String traversal using for range

Specific cases are as follows:

```package main
import "fmt"

func main() {
//1. For range traversal string
str := "Eastmount CSDN"
for index, val := range str {
fmt.Printf("index=%d, value=%c \n", index, val)
}

//2. For range traversal array
nums := []int{2, 3, 4}
for i, num := range nums {
fmt.Printf("index=%d, value=%d \n", i, num)
}
}
```

The output results are shown in the figure below: If our string contains Chinese, the traditional way of traversing the string will be wrong and garbled. The reason is that the traditional traversal of strings is based on bytes, while a Chinese character corresponds to three bytes in utf8 encoding. How to solve it? You need to convert str to [] run slice.

rune The bottom layer of string in golang is implemented through byte array. Chinese characters occupy 2 bytes in unicode and 3 bytes in utf-8 encoding, while the default encoding of golang is utf-8. rune is equivalent to int32 and is commonly used to handle unicode or utf-8 characters. The specific code is shown below.

```package main
import "fmt"

func main() {
//1. String traversal - traditional method
str := "CSDN!Xiu Zhang"
str2 := []rune(str)           //Convert str to [] run
for i := 0; i < len(str2); i++  {
fmt.Printf("index=%d, value=%c \n", i, str2[i])
}
fmt.Println("")

//2. String traversal - for range
for index, val := range str {
fmt.Printf("index=%d, value=%c \n", index, val)
}
fmt.Println("")

//3. If you don't turn to run, you can traverse directly (garbled code)
for i := 0; i < len(str); i++  {
fmt.Printf("index=%d, value=%c \n", i, str[i])
}
}
```

The output results are shown in the figure below. The first two methods are correct (traversal by bytes), and the third method will appear garbled. ## 3. Classic case of for programming

The following describes the cases of loops in various programming languages. Calculate the number and sum of 1 to 100.

```package main
import "fmt"

func main() {
var result = 0
var num = 0
for i := 1; i <= 100; i++ {
result += i
num++
}
fmt.Println("1+2+...+100 =", result)
fmt.Println("number =", num)
}
```

The output results are shown in the figure below: The flow chart is shown in the figure below: ## 4. Similar to while and do while loops

Because Golang only has a for loop, without the while keyword and do while syntax, it can only simulate while and do while loops through a for loop, that is, it can be implemented using for+break.

(1) while loop The core code of the for loop simulating the while loop is shown in the following figure. Note:

• The for loop is an infinite loop
• The break statement is to jump out of the for loop while loop statements similar to Java or C language:

```int i = 0;
while(i<10){    // notice there is only <
do something
}
```

The case is as follows. Use while to output 10 sentences of "hello world".

```package main
import "fmt"

func main() {
//Similar to a while loop
var i int = 1
for {
//Cycle condition
if i > 10 {
break           //End cycle
}
fmt.Println("hello world", i)
i++
}
}
```

The output results are shown in the figure below: (2) Do while loop Because do while is executed before judgment, the core code of the for loop simulating do while loop is shown in the following figure: Note:

• Because do while is executed before judgment, it is executed at least once
• When the loop condition is established, it will execute break and jump out of the for loop
```package main
import "fmt"

func main() {
//Use do while to output 10 sentences of "hello world"
var j int = 1
for {
//Execute before Judge
fmt.Println("hello world", j)
j++
if j > 10 {
break           //End cycle
}
}
}
```

# 2, Multiple cycle control

The specific meaning is:

• A nested loop is formed when one loop is placed in another loop. The outer for loop is called the outer loop, and the inner for loop is called the inner loop. It is recommended to generally use two layers, no more than three layers at most.
• In essence, nested loops regard the inner loop as the loop body of the outer loop. When the loop condition of the inner loop is false, it will completely jump out of the inner loop, end the current loop of the outer loop and start the next loop.
• Let the outer layer cycle times be m times and the inner layer cycle times be n times, then the inner layer cycle body actually needs to execute m*n times.

The following is a multi cycle understanding through a case, which is also a difficulty and focus of the cycle. As Mr. Han said, difficulties in programming are very common. We need to pay attention to:

• First easy, then difficult, decompose a complex problem into simple problems.
• Die first and live later, and slowly change the code from rigid to flexible.
• Learn to solve problems. Learn to use search engines or forums to solve problems independently.

## Case 1: Round Robin average

Title: count the results of three classes. There are four students in each class. Calculate the average score of each class and the average score of all classes. Students' grades are entered from the keyboard.

• Problem solving ideas First, learn to count the results of a class and calculate the average score of the class. The class has 4 students; Then consider the case of three shifts through cyclic calculation.
```package main
import "fmt"

func main() {
//Calculate the average score of each class and the average score of all classes (there are 4 students in each class of 3 classes)
//Problem solving: the number of classes in the outer circle and the average score of each class are calculated in the memory circle
var totalsum float64 = 0.0
for j := 1; j <= 3; j++ {
var sum float64 = 0.0
for i := 1; i <= 4; i++ {
var score float64
fmt.Scanln(&score)
//Cumulative total score
sum += score
}
fmt.Printf("The first%d What is the average score of each class%v \n", j, sum / 4)
//Calculate the summary results of each class
totalsum += sum
}
fmt.Printf("The total score of each class is%v The average score is%v \n", totalsum, totalsum / (4* 3))
}
```

The output results are shown in the figure below: At the same time, in order to write code more flexibly, we can try to modify 3 classes and 4 students of loop control constant into variables, as follows:

• var classNum int = 3
• var stuNum int = 4
```package main
import "fmt"

func main() {
//Calculate the average score of each class and the average score of all classes (there are 4 students in each class of 3 classes)
//Problem solving: the number of classes in the outer circle and the average score of each class are calculated in the memory circle
var classNum int = 3
var stuNum int = 4
var totalsum float64 = 0.0

for j := 1; j <= classNum; j++ {
var sum float64 = 0.0
for i := 1; i <= stuNum; i++ {
var score float64
fmt.Scanln(&score)
//Cumulative total score
sum += score
}
//Note that the golang data type needs consistent conversion to operate int - > float64
fmt.Printf("The first%d What is the average score of each class%v \n", j, sum / float64(stuNum))
//Calculate the summary results of each class
totalsum += sum
}
result := totalsum / float64(stuNum * classNum)
fmt.Printf("The total score of each class is%v The average score is%v \n", totalsum, result)
}
```

If we need to continue to count the number of passing classes, how can we achieve it?

• Compare the if judgment statements ## Case 2: circular printing of pyramids and inverted triangles

Printing pyramid is a classic case, which was also arranged in the second article above. Next, we print various pyramids through the for loop. The idea is as follows:

• Two layer loop, one controls the number of pyramid layers, and the other controls the output of each layer
• Printed graphics are usually composed of characters and spaces to find the corresponding rules
• From simple to complex, for example, print a rectangle first, then try half a triangular pyramid, and then print a complete pyramid

First, we introduce the code of printing rectangle and half triangle pyramid.

```package main
import "fmt"

func main() {
var totalLevel int = 5

//1. Print rectangle
for i := 1; i <= totalLevel; i++ {     //i represents the number of layers
for j := 1; j <= totalLevel; j++ { //Output per layer
fmt.Print("*")
}
fmt.Println()  //Line feed
}
fmt.Println()

//2. Print positive triangle half pyramid
for i := 1; i <= totalLevel; i++ {   //i represents the number of layers
for j := 1; j <= i; j++ {        //Output per layer
fmt.Print("*")
}
fmt.Println()  //Line feed
}
fmt.Println()

//3. Print the inverted triangle half pyramid
for i := 1; i <= totalLevel; i++ {   //i represents the number of layers
for j := (totalLevel - i); j >= 0; j-- {       //Output per layer
fmt.Print("*")
}
fmt.Println()  //Line feed
}
}
```

The output results are shown in the figure below: After understanding the above code, we can print the pyramid. The rule is:

```Space + * + Space

*           1 1 layer* law: 2*Number of layers-1   Space 4 rules:Total layers-Current layers
***          2 3 layers* law: 2*Number of layers-1   Space 3 rules:Total layers-Current layers
*****
*******
*********
```

The complete code is as follows, including solid pyramid and hollow pyramid.

```package main
import "fmt"

func main() {
/* Print pyramid
*           1 Layer 1 * rule: 2 * number of layers - 1 space 4 rules: total number of layers - current number of layers
***          2 Layer 3 * rules: 2 * number of layers - 1 space 3 rules: total number of layers - current number of layers
*****
*******
*********
*/

var totalLevel int = 5

//Method 1: print a solid pyramid
for i := 1; i <= totalLevel; i++ {               //i represents the number of layers
//Print spaces first
for j := (totalLevel - i); j >= 0; j-- {
fmt.Print(" ")
}
//Print asterisk
for k := (2 * i - 1); k > 0; k-- {
fmt.Print("*")
}
fmt.Println()  //Line feed
}
fmt.Println()

//Method 2: print hollow pyramid
for i := 1; i <= totalLevel; i++ {               //i represents the number of layers
//Print spaces first
for j := 1; j <= (totalLevel - i); j++ {
fmt.Print(" ")
}
//Print asterisk
for k := 1; k <= (2 * i - 1); k++ {
//First and last print of each layer * print all at the bottom layer*
if k == 1 || k == (2 * i - 1) || i == totalLevel {
fmt.Print("*")
} else {
fmt.Print(" ")
}
}
fmt.Println()  //Line feed
}
}
```

The output results are shown in the figure below: # 3, Jump control statement

## 1.break

The break statement is used to terminate the execution of a statement block, interrupt the current for loop or jump out of the switch statement. The basic syntax is as follows:

```{
....
break
....
}
```

The schematic diagram is shown in the figure below (quoted from Mr. Han). Firstly, a simple case is introduced in combination with the previous 1 + 2 +... + 100 to find the sum of the current number greater than 20 for the first time.

```package main
import "fmt"

func main() {
//Find the current number when the sum is greater than 20 for the first time
sum := 0
for i := 1; i <= 100; i++ {
sum += i   //Sum
if sum > 20 {
fmt.Println("sum When greater than 20, the current number is", i)
break  //Jump out of loop
}
}
}
```

The output results are shown in the figure below: Precautions for break statement:

• break statements appear in multi-layer nested statement blocks. Labels can indicate which layer of statement blocks to terminate
• break will jump out of the nearest for loop by default
• After break, you can specify a label and jump out of the for loop corresponding to the label

The code for specifying the layer by jumping out of the for loop through the label is as follows:

```package main
import "fmt"

func main() {
//Specify the layer by jumping out of the for loop through the label
label1:
for i := 0; i < 4; i++ {
//label2:
for j := 0; j < 10; j++ {
if j ==2 {
//The default is to jump out of the nearest loop. Here, try to jump out of the outer loop
break label1
}
fmt.Println("j =", j, "i =", i)
}
}
}
```

The operation results are as follows. When j is equal to 2, all cycles will jump out, that is, switch to label1 ## 2.continue

The continue statement is used to end this loop and will continue to execute the next loop. The basic syntax is as follows:

```{
...
continue
...
}
```

The flow chart is shown below. It will end this cycle and continue to iterate to execute the next cycle. Similarly, when the continue statement appears in the multi-layer nested loop statement body, you can indicate which layer of loop to skip through the label, which is the same as the use rule of the previous break label.

I don't like the function of jumping out of the specified loop layer. I feel that the code is not well controlled. Especially for large projects, it is recommended to jump out in combination with actual judgment conditions. Of course, the author's understanding ability is still shallow. If readers have good application scenarios, they can share them with me, thank you.

Take a simple example:

```package main
import "fmt"

func main() {
//continue jumps out of the current loop
for i := 0; i < 4; i++ {
for j := 0; j < 10; j++ {
if j ==2 {
continue
}
fmt.Println("j =", j, "i =", i)
}
}
}
```

The output result is shown in the figure below. j=2 is not output every time. If we need to print odd numbers within 100 using continue, we can write the following code: # 4, goto statement

The goto statement in Golang can be transferred unconditionally to the specified line in the program. Goto is often used with conditional statements to realize conditional transfer or jump out of the loop body. Note that goto statement is generally not advocated in GO programming to avoid confusion in the process and difficulties in understanding and debugging the program. Similarly, C language is not advocated.

```goto label
....
label: statement
```

The execution process is shown in the figure below: Here is a simple case:

```package main
import "fmt"

func main() {
//goto Statement
fmt.Println("aaaaa")
var n int = 30
if n > 20 {
goto label
}
fmt.Println("bbbbb")
fmt.Println("ccccc")
label:
fmt.Println("ddddd")
fmt.Println("eeeee")
fmt.Println("fffff")
}
```

The output results are shown in the figure below: # 5, Jump control statement return

return is used in a method or function to jump out of the method or function. When sharing functions, I will introduce them in detail.

return instructions:

• If return is an ordinary function, it means that the function jumps out, that is, the code behind return in the function is no longer executed, which can also be understood as terminating the function.
• If return is in the main function, it means that the main function is terminated, that is, the program is terminated.
```package main
import "fmt"

func main() {
//return statement
for i := 1; i<=10; i++ {
if i==3 {
return
}
fmt.Println("Output results", i)
}
fmt.Println("over")
}
```

The output results are shown in the figure below: # 6, Golang programming exercise

## 1. Title

(1) Print the number and sum of all integers between 1 and 100 that are multiples of 9.

(2) Loop to output all characters of "East xiuzhang" string in turn.

(3) Print 9 * 9 multiplication table.

(4) Simulate the website login verification mechanism. Suppose there are three opportunities. If the user name is "Eastmount" and the password is "666666", it will prompt that the login is successful, otherwise it will prompt the remaining opportunities; Finally, if it exceeds 3 times, it will prompt "too many input errors, unable to log in".

(5) Randomly generate a number from 1 to 100. If 99 is generated, it will stop. Calculate how many times it is used.

(6) Enter the following 4 * 5 matrix.

```1       2       3       4       5
2       4       6       8       10
3       6       9       12      15
4       8       12      16      20
```

(7) Find the first 10 numbers of Fibonacci sequence by cycle. (8) Find all prime numbers between 2 and 200.

(1) Print the number and sum of all integers between 1 and 100 that are multiples of 9.

The code is as follows:

```package main
import "fmt"

func main() {
var max int = 100
var count int = 0
var sum int = 0
for i := 1; i <= max; i++ {
if i % 9 == 0 {
count++
sum += i
}
}
fmt.Printf("count=%v sum=%v \n", count, sum)
}
```

The output results are shown in the figure below: (2) Loop to output all characters of "East xiuzhang" string in turn. Using range on the array passes in two variables, index and value. If we do not need to use the sequence number of the element, we use the blank character "" to omit.

```package main
import "fmt"

func main() {
str := "East=Xiu Zhang"

//Method 1
fmt.Printf("utf-8 Traversal string\n")
for _, s := range str {
fmt.Printf("utf-8 ergodic: %c %v \n", s, s)
}
fmt.Println("")

//Method 2
str2 := []rune(str)
for i := 0; i < len(str2); i++  {
fmt.Printf("utf-8 ergodic: index=%d, value=%c \n", i, str2[i])
}
fmt.Println("")

//Method 3 garbled code
fmt.Printf("unicode Traversal string\n")
for i := 0; i < len(str); i++ {
ch := str[i]
fmt.Printf("unicode ergodic: %c  %d\n", ch, ch)
}
}
```

The output results are shown in the figure below: (3) Print 9 * 9 multiplication table.

The code is as follows:

```package main
import "fmt"

func main() {
//9 * 9 multiplication table
var num int = 9
for i := 1; i <= num; i++ {
for j := 1; j <= i; j++ {
fmt.Printf("%v*%v=%v \t", j, i, j*i)
}
fmt.Println()
}
}
```

The output results are shown in the figure below: (4) Simulate the website login verification mechanism. Suppose there are three opportunities. If the user name is "Eastmount" and the password is "666666", it will prompt that the login is successful, otherwise it will prompt the remaining opportunities; Finally, if it exceeds 3 times, it will prompt "too many input errors, unable to log in".

The code is as follows:

```package main
import "fmt"

func main() {
var name string
var pwd string

for i := 1; i <= 3; i++ {
//Input information
fmt.Println("enter one user name")
fmt.Scanln(&name)
fmt.Scanln(&pwd)

if name == "Eastmount" && pwd == "666666" {
break
} else {
fmt.Printf("Input error, you still have%v Second chance\n", loginChance)
}
}
}
}
```

The output results are shown in the figure below: (5) Randomly generate a number from 1 to 100. If 99 is generated, it will stop. Calculate how many times it is used.

• Tip: this topic simulates the break statement in an infinite loop, randomly generates numbers through rand.Seed(), and then makes a judgment
```package main
import (
"fmt"
"math/rand"
"time"
)

func main() {
//Randomly generate a number from 1 to 100. If 99 is generated, it will stop
var count int = 0
for {
//Seed generation uses the uncertainty of system time for initialization
rand.Seed(time.Now().UnixNano())
num := rand.Intn(100) + 1
fmt.Println("num =", num)
count++
if (num == 99) {
break
}
}
fmt.Println("Generate random number 99 total usage times =", count)
}
```

The output results are shown in the figure below: (6) Enter the following 4 * 5 matrix.

The code is as follows:

```package main
import "fmt"

func main() {
var n int = 4
var m int = 5
var res int = 0
for i := 1; i <= n; i++ {
for j := 1; j <= m; j++ {
fmt.Printf("%v\t", i*j)
res++
}
fmt.Println("")
}
}
```

The output results are shown in the figure below: (7) Find the first 10 numbers of Fibonacci sequence by cycle.

• The characteristic of this function is that the first and second numbers are 1, and from the third number is the sum of the first two numbers. The corresponding process of problem-solving ideas is shown in the figure below: ```package main
import "fmt"

func main() {
//Fibonacci sequence
var f1 int = 1
var f2 int = 1
var f3 int

fmt.Printf("%v\n%v\n", f1, f2)
for i := 1; i <= 10; i++ {
f3 = f1 + f2
fmt.Printf("%v\n", f3)
f1 = f2
f2 = f3
}
}
```

The output results are shown in the figure below: (8) Find all prime numbers between 2 and 200.

• Solution idea: enter n. if n cannot be divided by any integer between 2 and sqrt(n) or 2 to n/2, it is a prime number. Of course, 2 to (n-1) division is the most primitive method. The corresponding algorithm flow is as follows: The code is as follows:

```package main
import "fmt"

func main() {
//Find all prime numbers between 2 and 200
var n int
var k int
var i int
var m int = 0

for n = 2; n <= 200; n++ {
k = n / 2
//If n is divided by i, the inner loop is terminated
for i = 2; i <= k; i++ {
if n % i == 0 {
break
}
}
//If I > K + 1, n is not divisible
if i >= k + 1 {
fmt.Printf("%d\t", n)
//m control line feed output 10 prime line feeds
m = m + 1
if m % 10 == 0 {
fmt.Println()
}
}
}
}
```

The operation results are shown in the figure below: # 7, Summary

After writing here, this basic Golang article has been introduced. I hope you like it! I wish you a happy new year, and I hope you can share more in-depth articles.

• 1, for loop control 1. Basic grammar 2. For range cycle 3. Classic case of for programming 4. Similar to while and do while loops
• 2, Multiple cycle control Case 1: Round Robin average Case 2: circular printing of pyramids and inverted triangles
• 3, Jump control statement 1.break 2.continue
• 4, goto statement
• 5, Jump control statement return
• 6, Golang programming exercise 1. Title 2. Answer

After understanding the basic operation and binary conversion of Go, the following articles will introduce the knowledge of conditional statements and circular statements of Go language in detail, and popularize them in combination with cases. I hope this basic article is helpful to you. Please forgive me if you don't write well. At the same time, I am very grateful to the leaders in the references for sharing their articles, especially Mr. Han Shunping, who knows that he is very good and has to work hard. I also hope I can Go deep into it. In the next four years, I will study the Go programming language, do more practical projects, write better articles and encourage each other!

• https://github.com/eastmountyxz/Go-learning

In 2020, the green tiles in github were finally pasted, submitted more than 2100 times in the first year, won more than 1500 + stars, opened 93 warehouses and 300 fans. I'm very happy. I hope I can stick to punching in github for five years and urge myself to move forward.

In a brief summary, the most satisfactory resource is the public opinion and emotional analysis shared in February last year when YQ broke out, and use this series of warm codes to cheer for Wuhan; The Python image recognition series is highly praised, and it has also been supplemented by the first contribution from foreign developers; The most time-consuming is the Wannacry reverse series, which took two months of reverse analysis, almost becoming the most detailed analysis of the worm in the whole network; There are also AI series, knowledge map actual combat, CVE reproduction, APT report, etc.

Of course, there are also many deficiencies. I hope to share higher quality resources in the coming year. I also hope to summarize the series of papers on safety and AI summit. I sincerely hope they can help you. Thank you and come on~ The newly opened "Na Zhang AI security home" on August 18, 2020 mainly focuses on Python big data analysis, cyberspace security, artificial intelligence, Web penetration and attack and defense technology, and shares the algorithm implementation of the paper. Nazhang's home will be more systematic and reconstruct all the author's articles, explain Python and security from zero, and have written articles for nearly ten years. I really want to share what I have learned, felt and done. Please give me more advice! thank you

reference:

• Go official website: https://golang.org/
• https://www.bilibili.com/video/BV1pt41127FZ
• https://www.runoob.com/go/go-tutorial.html
• https://studygolang.com/pkgdoc
• C programming, Mr. Tan Haoqiang