×

Golang Tutorial

Golang Reference

Golang Programs

Golang Practice

Golang Miscellaneous

Golang for Loop | Find Output Programs | Set 3

This section contains the for loop find output programs (set 3) with their output and explanations.
Submitted by Nidhi, on August 14, 2021

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)
	}
}

Output:

arr[ 0 ]:  1
arr[ 1 ]:  2
arr[ 2 ]:  3
arr[ 3 ]:  4
arr[ 4 ]:  5

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.


Program 2:

package main

import "fmt"

func main() {
	arr := []int{1, 2, 3, 4, 5}

	for _, value = range arr {
		fmt.Print(value, " ")
	}
}

Output:

./prog.go:8:9: undefined: value
./prog.go:9:13: undefined: value

Explanation:

The above program will generate errors because the variable value is not defined. The correct program is given below,

package main

import "fmt"

func main() {
	arr := []int{1, 2, 3, 4, 5}

	for _, value := range arr {
		fmt.Print(value, " ")
	}
}

// Output: 1 2 3 4 5 

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)
	}
}

Output:

Student detail:
101 : Amit
102 : Arun
103 : Anup

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.


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)
	}
}

Output:

Student detail:
101
102
103

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.


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)
	}
}

Output:

Student detail:
Amit
Arun
Anup

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.

Golang Find Output Programs »





Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.