[Golang program flow control]

Posted by CarbonCopy on Sun, 06 Feb 2022 08:46:05 +0100

1, Introduction to program flow control

  • Sequential control
  • Branch control
  • Cycle control

2, Sequential control

1) Connotation

2) Flow chart

3) Note = = the definition variable adopts legal forward reference

3, Branch control

1. Basic introduction of branch control

  • Single branch
  • Double branch
  • Multi branch

2. Single branch control

1) Basic grammar

	age:=12
	var age int
	fmt.Println("Please enter your age:")
	fmt.Scanln(&age)
	if age>=18 {
		fmt.Println("You are responsible for your actions")
	}

2) Flow chart

3) Details: in if, it supports defining a variable

	if age:=20;age>18{//I think this is a little magical. It supports defining a variable in the if judgment condition
		fmt.Println("You are older than 18 and should be responsible for your actions!")

3. Multi branch control

1) Basic grammar

else is not required, and multiple branches have only one execution entry
2) Flow chart
3) Some attention
4) Case

package main
import "fmt"
func main(){
	var score int 
	fmt.Println("Please enter your grade:")
	fmt.Scanln(&score)
	if score==100{
		fmt.Println("Reward one BMW")
	}else if score>88&&score<=99{
		fmt.Println("Reward one iphone7plus")
	}else if score>=60&&score<=80{
		fmt.Println("Reward one Ipad")
	}else{
		fmt.Println("Nothing")
	}
}


package main
import "fmt"
func main(){
	var height int32
	var money float64
	var handsome bool
	fmt.Println("Please enter your height:")
	fmt.Scanln(&height)
	fmt.Println("Please enter Wealth:")
	fmt.Scanln(&money)
	fmt.Println("Please enter whether you are handsome:")
	fmt.Scanln(&handsome)
	if height>180 && money>1.0 &&handsome{
		fmt.Println("I must marry him")
	}else if height>180 || money>1.0 || handsome{
		fmt.Println("Marry, not enough than the top, more than the bottom.")
	}else{
		fmt.Println("Don't marry....")
	}
}


package main
import (
	"fmt"
	"math"
)
func main(){
	a:=2.0
	b:=4.0
	c:=2.0
	m:=b*b-4*a*c
	if m>0{
		x1:=(-b+math.Sqrt(m))/2*a
		x2:=(-b-math.Sqrt(m))/2*a
		fmt.Printf("x1=%v x2=%v",x1,x2)
	}else if m==0{
		x1:=(-b+math.Sqrt(m))/2*a
		fmt.Printf("x1=%v",x1)
	}else{
		fmt.Println("unsolvable")
	}
}

5) Trap

The conditional expression of if cannot be an assignment statement

4. Nested branches

1) Basic introduction
2) Case

package main
import(
	"fmt"
)
func main(){
	var second float64
	fmt.Println("Please enter the number of seconds")
	fmt.Scanln(&second)
	if second<=8{
		var gender string
		fmt.Println("Please enter gender")
		fmt.Scanln(&gender)
		if gender=="female"{
			fmt.Println("Enter the women's group")
		}else{
			fmt.Println("Enter the men's group")
		}
	}else{
		fmt.Println("Out")
	}
}

4, SWITCH branch control

1) Don't add break to the introduction
2) Flow chart
3) Quick start cases

func main(){
	var key byte
	fmt.Println("Please enter a character, a,b,c,d,e")
	fmt.Scanf("%c",&key)
	switch key {
		case 'a':
			fmt.Println("Monday")
		case 'b':
			fmt.Println("Tuesday")
		case 'c':
			fmt.Println("Wednesday")
		case 'd':
			fmt.Println("Thursday")
		case 'e':
			fmt.Println("Friday")
		default:
			fmt.Println("Incorrect input...")
	}
}


4) Pay attention to details

  • The data types of expressions after case and switch are consistent
  • There can be multiple expressions after case, separated by commas
  • The expression after case is a constant and cannot be repeated
  • Do not need to break after case
  • default is not required
  • Switch is used without an expression, similar to if else
func main(){
	age:=10
	switch {
		case age==10:
			fmt.Print("excellent")
		case age<10 && age>=5:
			fmt.Print("excellent")
		case age<5 && age>=0:
			fmt.Print("come on.")
		default :
			fmt.Print("It's hopeless")
	}
}

  • A variable can be defined after switch, which is not recommended
  • fallthrough penetration, the next case can be executed

    5) Practice
func main(){
	var month byte
	fmt.Println("Please enter the month:")
	fmt.Scanln(&month)
	switch month{
	case 3,4,5:
		fmt.Println("spring")
	case 6,7,8:
		fmt.Println("summer")
	case 9,10,11:
		fmt.Println("autumn")
	case 12,1,2:
		fmt.Println("winter")
	default:
		fmt.Println("Input error")
	}
}

5, FOR cycle control

1) Quick start

func main(){
	for i:=1;i<=10;i++{
		fmt.Println("hello world")
	}
}


2) Basic grammar
3) Flow chart
4) Attention

  • The loop condition returns an expression with a Boolean value
  • The second way to use
	j:=1
	for j<=10 {
		fmt.Println("hello world!")
		j++;
	}
  • The third way
	j:=0;//Infinite loop with break
	for{
			if(j<10){
				fmt.Println("hello world")
			}else{
				break
			}
			k++
	}
  • for-range

6, WHILE and DO... Implementation of WHILE

1) Implementation of while

2) Implementation of dowile

7, Multiple cycle control

1) Basic introduction
2) Case

	totalsum:=0.0
	for j:=1;j<=3;j++{
	sum:=0.0
	for i:=1;i<=5;i++{
		var score float64
		fmt.Println("Please enter student grade:")
		fmt.Scanln(&score)
		sum+=score
	}
	fmt.Println("The first%d The average score of each class is:%v",j,sum/5)
	totalsum+=sum
	}
	fmt.Printf("Total score:%v",totalsum)

Print pyramid

	 for i:=1;i<=3;i++{
		for k:=1;k<=3-i;k++{
			fmt.Print(" ")
		}
		for j:=1;j<=2*i-1;j++{
			fmt.Print("*")
		}
		fmt.Println()
	}

8, Jump control statement

1.BREAK

1) Introduce break

func main(){
	// rand.Seed(time.Now().Unix())
	// n:=rand.Int(100)+1
	// fmt.Println(n)
	count:=0
	for{
		rand.Seed(time.Now().UnixNano())
		n:=rand.Intn(100)+1
		fmt.Println("n=",n)
		count++
		if(n==99){
			
			break
		}
	}
	fmt.Printf("Total use%d second",count)
}


2) Basic introduction
3) Schematic diagram
4) Note that the multi-layer loop exits that layer loop through label control

5) Practice

	sum:=0
	for i:=1;i<=100;i++{
		sum+=i
		if sum>20{
			fmt.Println("Current number:",i)
			break
		}
	}

2.CONTINUE

1) Introduction
2) Practice

	var p int
	var n int
	var num int
	for{
		fmt.Scanln(&num)
		if num==0{
			break
		}
		if num>0{
			p++
			continue
		}
		n++
	}
	fmt.Printf("Number of positive numbers%v,Number of negative numbers%v",p,n)
}

3.GOTO

1) Basic introduction
2) Quick start

	n:=30
	if n>20{
		goto label
	}
	fmt.Println("ok1")
	fmt.Println("ok2")
	fmt.Println("ok3")
	label:
	fmt.Println("ok6")
	fmt.Println("ok7")
	fmt.Println("ok8")

4.RETURN

func main(){
	for i:=1;i<=10;i++{
		if i==3{
			return 	
		}
		fmt.Println("doll",i)
	}
	fmt.Println("hello world!")
}


ps: if you change return to break, the result becomes

summary

Tip: This article only briefly introduces the process control of Golang program. This article is a note made through the learning of Golang video in station b.

Topics: Go Back-end