Golang Basics | Find Output Programs | Set 4

This section contains the Golang basics find output programs (set 4) with their output and explanations.
Submitted by Nidhi, on August 10, 2021

Program 1:

package main

import "fmt"

func main() {
	var num1 int = 0
	var num2 int = 0

	fmt.Print("Enter the value of num1 and num2: ")
	fmt.Scanf("%d%d", num1, num2)

	fmt.Println("Addition is: ", num1+num2)
}

Output:

Enter the value of num1 and num2: 10 20
Addition is:  0

Explanation:

In the above program, we read the value of num1 and num2 variables using fmt.Scanf() function but here we did not use the "&" operator to assign input value to the variables that why addition is 0.


Program 2:

package main

import "fmt"

func main() {
	var num1 int = 0
	var num2 int = 0
	var num3 int = 0

	fmt.Print("Enter the value of num1 and num2: ")
	num3 = fmt.Scanf("%d%d", &num1, &num2)

	fmt.Println("Num1: ", num1)
	fmt.Println("Num2: ", num2)
	fmt.Println("Num3: ", num3)
}

Output:

./prog.go:11:7: assignment mismatch: 1 variable but fmt.Scanf returns 2 values

Explanation:

The above program will generate a syntax error. Because fmt.Scanf() function returns two values but we used only the num3 variable as an lvalue.


Program 3:

package main

import "fmt"

func main() {
	var num1 int = 0
	var num2 int = 0
	var num3 int = 0

	fmt.Print("Enter the value of num1 and num2: ")
	num3, _ = fmt.Scanf("%d%d", &num1, &num2)

	fmt.Println("Num1: ", num1)
	fmt.Println("Num2: ", num2)
	fmt.Println("Num3: ", num3)
}

Output:

Enter the value of num1 and num2: 10 20
Num1:  10
Num2:  20
Num3:  2

Explanation:

In the above program, we created three variables num1, num2, and num3. The fmt.Scanf() function returns the total number of variables read from the user. Then we printed the values of all variables.


Program 4:

package main

import "fmt"

func main() {
	var str string

	fmt.Print("Enter string: ")
	fmt.Scanf("%s", str)

	fmt.Println(str)
}

Output:

Enter string: Hello

Explanation:

The above program will not print the input string because while taking an input need to use the "&" operator.


Program 5:

package main

import "fmt"

func main() {
	var str string

	fmt.Print("Enter string: ")
	fmt.Scanf(&str)

	fmt.Println(str)
}

Output:

./prog.go:9:12: cannot use &str (type *string) as type string in argument to fmt.Scanf

Explanation:

The above program will generate a syntax error. Because we cannot use fmt.Scanf() function without specifying format specifiers.

Golang Find Output Programs »





All Golang Programs

Comments and Discussions!

Load comments ↻





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