×

Golang Tutorial

Golang Reference

Golang Programs

Golang Practice

Golang Miscellaneous

Golang Arrays | Find Output Programs | Set 3

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

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

Output:

Hello World

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.


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

Output:

str1
str2
str3
str4

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.


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

Output:

1 2 panic: runtime error: index out of range [2] with length 2

goroutine 1 [running]:
main.main()
	/tmp/sandbox1836064742/prog.go:11 +0xc5

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.


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

Output:

1 5 9 

Explanation:

In the above program, we created a 3X3 matrix. Then we printed left diagonal elements.


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

Output:

1 5 9 

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.

Golang Find Output Programs »





Comments and Discussions!

Load comments ↻





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