当前位置:网站首页>Go language for loop

Go language for loop

2022-06-11 21:04:00 Just number six Z

for sentence

A loop statement means that a condition is satisfied . You can execute a piece of code repeatedly .

for Is the only loop ,Go There is no while.

for The basic use of loops

Grammatical structure :

for init;condition;post{
      }

The initialization statement is executed only once . After initializing the loop , This condition will be checked . If the condition is calculated as true, Then the loop body in will be executed , And then there was post sentence .post Statement will be executed after each successful iteration of the loop . In execution post After statement , This condition will be rechecked . If it's right , The loop will continue , Otherwise the cycle ends .

for Other ways to write a loop

for All three components of the loop , It's all optional , Initialization 、 Conditions and post It's all optional .

(1) Also omit the expression 1 And expressions 3, amount to while loop

for  expression 2{
    
	
}

(2)for Cyclic range The format can be right slice、map、 Array 、 String to iterate over .

for key,value := range oldMap{
    
	newMap[key] = value
}

(3) Omit three expressions at the same time , amount to while(true), Equivalent to acting directly on true On .


for {
    

}

for Circulation practice

Exercise one : Print 18-23 Equal number

package main

import "fmt"

func main() {
    
	for i := 58; i >= 23 ; i-- {
    
		fmt.Println(i)
	}
}

Exercise 2 : seek 1-100 And

package main

import "fmt"

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

Exercise 3 : Print 1-100 Inside , It can be 3 to be divisible by , But can't be 5 Divisible numbers , Count the number of printed numbers , Print five per line .

package main

import "fmt"

func main() {
    
	count := 0
	for i := 1; i <= 100; i++ {
    
		if i % 3 == 0 && i % 5 != 0 {
    
			count ++
			fmt.Print(i,"\t")
			if count % 5 == 0 {
    
				fmt.Println()
			}
		}
	}
	fmt.Println()
	fmt.Println(" The number to be printed is ",count," individual ")
}

Multi level loop nesting

Exercise one : Print *, Five per line , Five lines altogether .

package main

import "fmt"

func main() {
    
	for i := 0; i < 5; i++ {
    
		for j := 0; j < 5; j++ {
    
			fmt.Printf("*")
		}
		fmt.Println()
	}
}

Exercise 2 : Print the multiplication table

package main

import "fmt"

func main() {
    
	for i := 1; i <= 9; i++ {
    
		for j := 1; j <= i; j++ {
    
			fmt.Printf("%d x %d = %d\t",j,i,i*j)
		}
		fmt.Println()
	}
}
原网站

版权声明
本文为[Just number six Z]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/162/202206112054045092.html