This section contains the Golang arrays find output programs (set 2) with their output and explanations.
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)
}
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)
}
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])
}
}
Program 4:
package main
import "fmt"
func main() {
var str string = "hello World"
for i := 0; i < len(str); i++ {
fmt.Println(str[i])
}
}
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()
}
Answer Program 1:
Output:
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.
Answer Program 2:
Output:
Explanation:
The above program will generate a syntax error because we have to pass array size with the array in function parameters.
Answer Program 3:
Output:
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.
Answer Program 4:
Output:
Explanation:
Here, we created a string str initialized with the "hello World". Then we printed the ASCII value of each character of the string.
Answer Program 5:
Output:
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.
need an explanation for this answer? contact us directly to get an explanation for this answer