Go Program to Add Two Numbers Using Functions

In this post, we will learn how to add two numbers using functions in the Go Programming language.

In the below example, we have created a user-defined function Add which passes two numbers as parameters and returns the sum of two numbers.

Within the main function, we call out the custom function to perform the addition of two numbers and get the result printed on the screen.

Go Program to Add Two Numbers Using Functions

package main

import "fmt"

func Add(a, b int) int {
	return a + b
}

func main() {
	var num1, num2, sum int

	fmt.Print("Enter the first number: ")
	fmt.Scanln(&num1)
	fmt.Print("Enter the second number: ")
	fmt.Scanln(&num2)

	sum = Add(num1, num2)

	fmt.Println("The sum of num1 and num2 is: ", sum)
}

Output

Enter the first number: 13
Enter the second number: 17
The sum of num1 and num2 is:  30

How Does This Program Work?

func Add(a, b int) int {
	return a + b
}

We have declared and defined a function named Add which passes two variables as parameters and performs the addition operation on those two variables.

	sum = Add(num1, num2)

We call out the custom function Add in the main function and pass the variables num1 and num2 as parameters.

Within the custom function, num1 and num2 are added using the + operator. The result returned from the custom function gets stored in the sum variable.

	fmt.Println("The sum of num1 and num2 is: ", sum)

In the end, the sum of num1 and num2 which is stored in the sum variable gets printed on the screen using the Println() function.

Conclusion

In this post, you learned how to add two numbers using functions in the Go Programming language.

If you have any doubts regarding the program, comment down your doubts in the comment section.

Leave a Comment

Your email address will not be published. Required fields are marked *