Golang program to create a user-defined function to add two integer numbers

Here, we are going to learn how to create a user-defined function to add two integer numbers in Golang (Go Language)?
Submitted by Nidhi, on March 10, 2021 [Last updated : March 03, 2023]

Adding two numbers using user-defined function in Golang

Problem Solution:

In this program, we will create a user-defined function addition() to add two integer numbers and return the result to the calling function.

Program/Source Code:

The source code to create a user-defined function to add two integer numbers is given below. The given program is compiled and executed successfully.

Golang code to create a user-defined function to add two integer numbers

// Golang program to create a user-defined function
// to add two numbers

package main

import "fmt"

func addition(num1 int, num2 int) int {
	var result int = 0

	result = num1 + num2

	return result
}
func main() {
	var num1 int = 0
	var num2 int = 0
	var result int = 0

	fmt.Print("Enter number1: ")
	fmt.Scanf("%d", &num1)

	fmt.Print("Enter number2: ")
	fmt.Scanf("%d", &num2)

	result = addition(num1, num2)

	fmt.Println("Addition is: ", result)
}

Output:

Enter number1: 36
Enter number2: 24
Addition is:  60

Explanation:

In the above program, we declare the package main. The main package is used to tell the Go language compiler that the package must be compiled and produced the executable file. Here, we imported the fmt package that includes the files of package fmt then we can use a function related to the fmt package.

In this program, we created a user defined function addition(), which is given below:

func addition(num1 int, num2 int) int { 
    var result int=0
    result=num1+num2    
    return result
}

The addition() function will accept two integer numbers and return the sum of both numbers to the calling function.

In the main() function, we created three variables num1, num2, which are initialized with 0. Then we read the value of num1, num2 from the user and we got the sum of both numbers by calling the addition() function and assigned it to the result variable. After that, we printed the result on the console screen.

Golang User-defined Function Programs »





Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.