This section contains the Golang arrays find output programs (set 3) with their output and explanations.
Program 1:
package main
import "fmt"
func main() {
var str string = "Hello World"
var ptr *string = &str
for i := 0; i < len(str); i++ {
fmt.Printf("%c", (*ptr)[i])
}
fmt.Println()
}
Program 2:
package main
import "fmt"
func main() {
var str = [4]string{"str1", "str2", "str3", "str4"}
var ptr *[4]string = &str
for i := 0; i <= 3; i++ {
fmt.Printf("%s\n", (*ptr)[i])
}
fmt.Println()
}
Program 3:
package main
import "fmt"
func main() {
var matrix = [2][2]int{{1, 1}, {2, 2}}
var i, j int = 0, 0
for i = 0; i < 2; i++ {
for j = 0; j < 2; i++ {
fmt.Printf("%d ", matrix[i][j])
}
fmt.Println()
}
fmt.Println()
}
Program 4:
package main
import "fmt"
func main() {
var matrix = [3][3]int{{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}
var i, j int = 0, 0
for i = 0; i < 3; i++ {
for j = 0; j < 3; j++ {
if i == j {
fmt.Printf("%d ", matrix[i][j])
}
}
}
fmt.Println()
}
Program 5:
package main
import "fmt"
func main() {
var matrix = [3][3]int{{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}
var i, j int = 0, 0
var ptr *[3][3]int = &matrix
for i = 0; i < 3; i++ {
for j = 0; j < 3; j++ {
if i == j {
fmt.Printf("%d ", (*ptr)[i][j])
}
}
}
fmt.Println()
}
Answer Program 1:
Output:
Explanation:
Here, we created a string str initialized with "Hello World" and also create the pointer ptr initialized with the address of str. Then we accessed the characters from the string one by one using the pointer and printed them.
Answer Program 2:
Output:
Explanation:
In the above program, we created an array of strings str and also create the pointer ptr initialized with the address of str. Then we accessed the strings one by one using the pointer and printed them.
Answer Program 3:
Output:
Explanation:
The above program will generate syntax error because we increased the value of i in the inner loop that's why we accessed elements from the index out of range of the array.
Answer Program 4:
Output:
Explanation:
In the above program, we created a 3X3 matrix. Then we printed left diagonal elements.
Answer Program 5:
Output:
Explanation:
In the above program, we created a 3X3 matrix and also created the pointer ptr which was initialized with the address of matrix. Then we printed left diagonal elements using the pointer.
need an explanation for this answer? contact us directly to get an explanation for this answer