In this post, we will learn how to add two numbers in the Go Programming language.
We will use two different approaches to add two numbers. The two different approaches are: –
- Using Standard Method
- Using User Input
In the first method, we will declare two variables and store the integers in them. Then, we will add those two variables.
In the second program, the two integers are taken as input from the user using Scanln() function. Then, the two variables are added, and the result is displayed on the screen.
Go Program to Add Two Numbers Using Standard Method
In this program, we will simply declare and define two variables, and return the sum of two numbers.
package main import "fmt" func main() { var sum = 0 num1 := 5 num2 := 13 sum = num1 + num2 fmt.Println("The sum of num1 and num2 is: ", sum) }
Output
The sum of num1 and num2 is: 18
How Does This Program Work?
var sum = 0
We have declared a variable “sum” which will store the addition of two numbers.
num1 := 5 num2 := 13
The two integers are stored in two different variables “num1” and “num2”.
sum = num1 + num2
The two variables are added using the + operator and the result is stored in the “sum” variable.
fmt.Println("The sum of num1 and num2 is: ", sum)
The sum of two variables is printed on the screen with the help of the Println() function.
The Println() function in the Go Programming language is a built-in function used to print out the output to the console.
Go Program to Add Two Numbers Using User Input
In this program, we will take the input from the user with the help of Scanln() function.
package main import "fmt" func main() { var num1, num2 int fmt.Print("Enter the first number: ") fmt.Scanln(&num1) fmt.Print("Enter the second number: ") fmt.Scanln(&num2) result := num1 + num2 fmt.Println("The sum of num1 and num2 is: ", result) }
Output
Enter the first number: 15 Enter the second number: 45 The sum of num1 and num2 is: 60
How Does This Program Work?
We will use the same logic as that of the above program. In this program, we will only alter the user input. Here, we will not define the variables, but rather ask the user to do so.
fmt.Print("Enter the first number: ") fmt.Scanln(&num1) fmt.Print("Enter the second number: ") fmt.Scanln(&num2)
The Scanln() function in the Go Programming language is used to read the standard input data.
The Scanln() function in this program reads the input given by the user and stores the value in the “num1” and “num2” variables respectively.
Then, the addition is performed on these two variables and the result is printed on the screen using the Println() function.
Conclusion
In this post, you learned two different approaches to adding two numbers.
First by using the standard method and second by taking user input.