Golang Arrays | Find Output Programs | Set 1

This section contains the Golang arrays find output programs (set 1) with their output and explanations.
Submitted by Nidhi, on September 29, 2021

Program 1:

package main

import "fmt"

func main() {
	var arr [5]int
	var i int
	var j int

	for i = 0; i < 5; i++ {
		arr[i] = i * 10
	}

	for j = i - 1; j >= 0; j-- {
		fmt.Println(arr[j])
	}
}

Output:

40
30
20
10
0

Explanation:

In the above program, we created an array of integer elements. Then we assigned the values to the array and printed them in reversed order.


Program 2:

package main

import "fmt"

var i int
var j int

func getJ() int {
	return j
}

func main() {
	var arr [5]int

	for i = 0; i < 5; i++ {
		arr[i] = i * 10
	}

	for j = i - 1; j >= 0; j-- {
		fmt.Println(arr[getJ()])
	}
}

Output:

40
30
20
10
0

Explanation:

In the above program, we created two global variables i, j and also created two functions getJ() and main(). The getJ() function returns the value of the global variable j. The main() function is the entry point for the program. Here, we created an array of integer elements. Then we assigned the values to the array and printed them in reversed order.


Program 3:

package main

import "fmt"

func main() {
	var arr [5]int
	var i, j int = 0, 0
	var p1, p2 *int = &i, &j

	for i = 0; i < 5; i++ {
		arr[*p1] = i * 10
	}

	for j = i - 1; j >= 0; j-- {
		fmt.Println(arr[*p2])
	}
}

Output:

40
30
20
10
0

Explanation:

In the above program, we created two variables i, j, and two pointers p1 and p2. The pointer p1 initialized with the address of i and pointer p2 initialized with the address of j. Then we created an array of integer elements. Then we assigned the values to the array and printed them in reversed order.


Program 4:

package main

import "fmt"

func main() {
	var arr [5]int
	var i, j int = 0, 0

	for i = 0; i < 5; i++ {
		arr[i] = i * 10
	}

	for j = i - 1; j >= 0; j-- {
		fmt.Println(*(arr + j))
	}
}

Output:

./prog.go:14:16: invalid operation: arr + j (mismatched types [5]int and int)

Explanation:

The above program will generate a syntax error because Go language does not support array accessibility like this.


Program 5:

package main

import "fmt"

func printArray(a [5]int) {
	var i int = 0
	for i = 0; i < 5; i++ {
		fmt.Println(a[i])
	}
}

func main() {
	var arr [5]int
	var i int = 0

	for i = 0; i < 5; i++ {
		arr[i] = i * 10
	}

	printArray(arr)
}

Output:

0
10
20
30
40

Explanation:

In the above program, we created two function printArray() and main(). The printArray() function accepts the array as an argument and prints the elements of the array.

In the main() function, we created the array and assigned values to the array elements. Then we called the printArray() function and printed the result.

Golang Find Output Programs »





Comments and Discussions!

Load comments ↻





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