This section contains the for loop find output programs (set 3) with their output and explanations.
Program 1:
package main
import "fmt"
func main() {
arr := []int{1, 2, 3, 4, 5}
for index, value := range arr {
fmt.Println("arr[", index, "]: ", value)
}
}
Program 2:
package main
import "fmt"
func main() {
arr := []int{1, 2, 3, 4, 5}
for _, value = range arr {
fmt.Print(value, " ")
}
}
Program 3:
package main
import "fmt"
func main() {
students := map[string]string{"101": "Amit", "102": "Arun", "103": "Anup"}
fmt.Println("Student detail:")
for roll, name := range students {
fmt.Printf("%s : %s\n", roll, name)
}
}
Program 4:
package main
import "fmt"
func main() {
students := map[string]string{"101": "Amit", "102": "Arun", "103": "Anup"}
fmt.Println("Student detail:")
for roll := range students {
fmt.Printf("%s\n", roll)
}
}
Program 5:
package main
import "fmt"
func main() {
students := map[string]string{"101": "Amit", "102": "Arun", "103": "Anup"}
fmt.Println("Student detail:")
for _, name := range students {
fmt.Printf("%s\n", name)
}
}
Answer Program 1:
Output:
Explanation:
In the above program, we created an array arr of integers. Then we used range to access index and value of array using for loop and printed the result on the console screen.
Answer Program 2:
Output:
Explanation:
The above program will generate errors because the variable value is not defined. The correct program is given below,
Answer Program 3:
Output:
Explanation:
In the above program, we created a map of students that contains roll-number and names. Then we accessed the student details from the map using the range in the for loop and printed the result on the console screen.
Answer Program 4:
Output:
Explanation:
In the above program, we created a map of students that contains roll-number and names. Then we accessed only keys from the map using the range in the for loop and printed the result on the console screen.
Answer Program 5:
Output:
Explanation:
In the above program, we created a map of students that contains roll-number and names. Then we accessed only values from the map using the range in the for loop and printed the result on the console screen.
need an explanation for this answer? contact us directly to get an explanation for this answer