在这个 Go 程序中,我们使用 for 循环进行迭代并查找数组元素,然后打印出索引位置。在这里,我们使用 If 语句 (if serArr[i] == search) 来检查数组中的任何元素是否等于搜索值。
一旦找到,flag 的值将变为 1 (flag = 1),然后 break 将会使 GC 跳出 for 循环。接下来,我们使用 If else 语句。如果 flag 等于 1 (if flag == 1),则表示我们在数组中找到了搜索项。否则,则表示未找到。
package main
import "fmt"
func main() {
var sersize, i, search int
fmt.Print("Enter the Even Array Size = ")
fmt.Scan(&sersize)
serArr := make([]int, sersize)
fmt.Print("Enter the Even Array Items = ")
for i = 0; i < sersize; i++ {
fmt.Scan(&serArr[i])
}
fmt.Print("Enter the Array Search Item = ")
fmt.Scan(&search)
flag := 0
for i = 0; i < sersize; i++ {
if serArr[i] == search {
flag = 1
break
}
}
if flag == 1 {
fmt.Println("We Found the Search Item ", search, " at position = ", i)
} else {
fmt.Println("We haven't Found the Search Item ")
}
}
Enter the Even Array Size = 3
Enter the Even Array Items = 10 20 30
Enter the Array Search Item = 20
We Found the Search Item 20 at position = 1
使用 For 循环 range 查找数组元素的 Go 程序
在此示例中,我们在循环内使用了 println 语句。它可以显示搜索到的元素。但是,这个 程序 如果找不到我们正在寻找的内容,则不会显示任何内容。
package main
import "fmt"
func main() {
var sersize, i, search int
fmt.Print("Enter the Even Array Size = ")
fmt.Scan(&sersize)
serArr := make([]int, sersize)
fmt.Print("Enter the Even Array Items = ")
for i = 0; i < sersize; i++ {
fmt.Scan(&serArr[i])
}
fmt.Print("Enter the Array Search Item = ")
fmt.Scan(&search)
for k, sr := range serArr {
if sr == search {
fmt.Println("We Found the Search Item ", search, " at position = ", k)
break
}
}
}
Enter the Even Array Size = 5
Enter the Even Array Items = 20 30 40 20 50
Enter the Array Search Item = 20
We Found the Search Item 20 at position = 0
在此查找数组元素的示例中,我们将 if-else 语句放在了循环外面,以显示未找到的结果。
package main
import "fmt"
func main() {
var sersize, i, search, pos int
fmt.Print("Enter the Even Array Size = ")
fmt.Scan(&sersize)
serArr := make([]int, sersize)
fmt.Print("Enter the Even Array Items = ")
for i = 0; i < sersize; i++ {
fmt.Scan(&serArr[i])
}
fmt.Print("Enter the Array Search Item = ")
fmt.Scan(&search)
flag := 0
for k, sr := range serArr {
if sr == search {
flag = 1
pos = k
break
}
}
if flag == 1 {
fmt.Println("We Found the Search Item ", search, " at position = ", pos)
} else {
fmt.Println("We haven't Found the Search Item ")
}
}
