ADVERTISEMENT
ADVERTISEMENT

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

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 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 »



ADVERTISEMENT


ADVERTISEMENT
ADVERTISEMENT


Comments and Discussions!

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.