Sum of two numbers in go lang
package main
import "fmt"
func main() {
var a,b int
a = 5
b = 10
sum := a + b
fmt.Println("Total = ",sum)
}
Explanation
- var a,b int: declare two variable a and b. Learn here how to create variable
- a = 5 and b = 10 assign 5,10 to a,b respectively
- sum:= a + b: adds a and b and store the result in sum as well as created sum variable with the short variable declaration (:=).
- fmt.Println("Total = ",sum): prints the result as Total = 15
Improvements
- Above program always returns fixed result Total = 15, because a and b are initialized with fixed value 5, 10 respectively.
- So this program can be improved by using user input.
- As well as above program variable declaration and initialization can be done in a single statement as shown here
var a,b int = 5 , 10
OR
var a,b = 5 , 10
Sum of two numbers with user input
package main
import "fmt"
func main() {
var a,b int
fmt.Print("Enter any two numbers: ")
fmt.Scan(&a,&b)
sum := a + b
fmt.Println("Total = ",sum)
}
Explanation
- In the above program, every you know except fmt.Scan( ) statement.
- fmt.Scan( ) statement means Scan() is a function available in fmt package and used to receive user input.
- While you receive the input, you need to pass the address of the variable in which you want to store input value.
- Example: &a stands for "address of a".
- Multiple variables can also be input by using Scan() function by separating each variable with comma as shown in the above program snippet.
- If you are previously C programmer then you can also use Scanf( ) function of fmt package to receive formatted input.
Comments