Golang examples to add/sum of two numbers or integers

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

Example: Sum of two numbers

In this program, variables are declared and initialized with 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

Here is an example program to sum numbers

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


Sum of two numbers:  13 

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

In this program, numbers are taken from the standard console. Scanln function is used to stop the control until the user is entered the number.

And the sum of these two numbers returns to the console.

package main  
import (  
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 the Second number: 34  
Sum of two numbers:  46  


In this short post, you learned sum or addition of numbers entered by a user and return the sum as a result to the console.

Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
You'll get a notification every time a post gets published here.