Golang examples to add/sum of two numbers or integers
- Admin
- Dec 31, 2023
- Golang-examples
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 the two numbers.
Example: Sum of two numbers in Golang
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 (
"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:
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. The 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 (
"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 the first number: 12
Please enter the Second number: 34
Sum of two numbers: 46
Conclusion
In this short post, you learned the sum or addition of numbers entered by a user and return the sum as a result to the console.