Go – Sum of Two Numbers
In this tutorial, we will learn how to find the sum of two numbers in the Go programming language (Golang). We’ll explore two methods: using variables directly and implementing a function for reusability. Each example will include the syntax, a program, and a detailed explanation to ensure a clear understanding of the concepts.
Syntax to Find Sum of Two Numbers
The basic syntax for adding two numbers in Go is:
var sum = num1 + num2
Here, num1
and num2
are the numbers to be added, and sum
holds the result of the addition.
Example 1: Sum of Two Numbers Using Variables
In this example, we will define two integer variables, add them, and store the result in a third variable. Finally, we will print the result to the console.
Program – example.go
package main
import "fmt"
func main() {
// Declare two variables
num1 := 10
num2 := 20
// Find the sum
sum := num1 + num2
// Print the result
fmt.Println("The sum of", num1, "and", num2, "is", sum)
}
Explanation of Program
1. We use the :=
syntax to declare and initialize two integer variables, num1
and num2
, with values 10 and 20, respectively.
2. The expression num1 + num2
calculates the sum of the two variables.
3. The result is stored in the sum
variable.
4. The fmt.Println
function is used to print the result to the console, along with descriptive text.
Output
Example 2: Sum of Two Numbers Using a Function
In this example, we will write a function to calculate the sum of two numbers. This approach makes the code reusable, as the function can be called multiple times with different inputs.
Program – example.go
package main
import "fmt"
// Function to find the sum of two numbers
func findSum(a int, b int) int {
return a + b
}
func main() {
// Call the function with two numbers
num1 := 15
num2 := 25
sum := findSum(num1, num2)
// Print the result
fmt.Println("The sum of", num1, "and", num2, "is", sum)
}
Explanation of Program
1. A function findSum
is defined, which takes two integer parameters a
and b
and returns their sum.
2. Inside the main
function, two integers, num1
and num2
, are initialized with values 15 and 25.
3. The findSum
function is called with num1
and num2
as arguments, and the result is stored in the sum
variable.
4. The fmt.Println
function is used to print the result to the console, along with descriptive text.