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

  1. var a,b int: declare two variable a and b. Learn here how to create variable
  2. a = 5 and b = 10 assign 5,10 to a,b respectively
  3. sum:= a + b:  adds a and b and store the result in sum as well as created sum variable with the short variable declaration (:=). 
  4. fmt.Println("Total = ",sum): prints the result as Total = 15

Improvements

  1. Above program always returns fixed result Total = 15, because a and b are initialized with fixed value 5, 10 respectively.
  2. So this program can be improved by using user input.
  3. 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

  1. In the above program, every you know except fmt.Scan( ) statement. 
  2. fmt.Scan( ) statement means Scan() is a function available in fmt package and used to receive user input.
  3. While you receive the input, you need to pass the address of the variable in which you want to store input value.
  4. Example: &a stands for "address of a".
  5. Multiple variables can also be input by using Scan() function by separating each variable with comma as shown in the above program snippet.
  6. If you are previously C programmer then you can also use Scanf( ) function of fmt package to receive formatted input.

Comments

Popular posts from this blog

Overview of Go lang

Arrays in C Language

Data Types in Go language

Creating your first html page

Say Hello world in Go lang

Arrays in Go lang

Installing go lang

String in golang

Decision Making in Go lang

Floating point Data types in Go lang