×

Golang Tutorial

Golang Reference

Golang Programs

Golang Practice

Golang Miscellaneous

Golang Arrays | Find Output Programs | Set 2

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

Program 1:

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 a pointer to an 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.


Program 2:

package main

import "fmt"

func printArray(a *[]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:

./prog.go:18:13: cannot use &arr (type *[5]int) as type *[]int in argument to printArray

Explanation:

The above program will generate a syntax error because we have to pass array size with the array in function parameters.


Program 3:

package main

import "fmt"

func main() {
	var arr [5]int
	var i int = 0
	var str string = "01234"

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

	for i = 0; i < 5; i++ {
		fmt.Println(arr[str[i]-0x30])
	}
}

Output:

0
10
20
30
40

Explanation:

In the above program, we created an array of integers, and created a string variable str initialized with "01234". Then we assigned the values to the array elements.

for i = 0; i < 5; i++ {  
    fmt.Println(arr[str[i]-0x30]);
}

In the main(), we accessed the array index by accessing character from string and convert it into an integer.


Program 4:

package main

import "fmt"

func main() {
	var str string = "hello World"

	for i := 0; i < len(str); i++ {
		fmt.Println(str[i])
	}
}

Output:

104
101
108
108
111
32
87
111
114
108
100

Explanation:

Here, we created a string str initialized with the "hello World". Then we printed the ASCII value of each character of the string.


Program 5:

package main

import "fmt"

func main() {
	var str string = "Hello World"

	for i := 0; i < len(str); i++ {
		fmt.Printf("%c", str[i])
	}
	fmt.Println()
}

Output:

Hello World

Explanation:

Here, we created a string str initialized with "Hello World". Then we accessed the characters from the string one by one and printed them.

Golang Find Output Programs »





Comments and Discussions!

Load comments ↻





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