Wednesday, December 12, 2018

Golang examples - Program to add/sum of two numbers or integers

In this program,  we have two programs to add two numbers. The First program, We will store the numbers and the addition of two numbers. The second program, take the two numbers from the user and return the sum of two numbers.

Example: Sum of two numbers 

In this program, variables are declared and did inline assignment statements. This is one way of declaring multiple variables of the same type in golang 
The same way can be rewritten using short assignment operator as below n1, n2, result := 10, 3, 0 .
The variable types can be inferred from right hand values
package main

import (
 "fmt"
)

func main() {
 var n1, n2, result = 10, 3, 0 // Declare variable and assign values
 result = n1 + n2
 fmt.Println("Sum of two numbers: ", result)

}
Output is
Sum of two numbers:  13 

Scanln function example -Sum numbers taken input from the standard console  

 In this program, numbers are taken from the standard console. Scanln function is used to stop the control until user is entered the number And sum of this two numbers are returned to console
package main

import (
 "fmt"
)

func main() {
 fmt.Print("Please enter first number: ")
 var n1 int
 fmt.Scanln(&n1) // take input from user
 fmt.Print("Please enter Second number: ")
 var n2 int
 fmt.Scanln(&n2) // take input from user
 result := n1 + n2
 fmt.Println("Sum of two numbers: ", result)

}
Output is
Please enter first number: 12
Please enter Second number: 34
Sum of two numbers:  46

Related article


EmoticonEmoticon