Introduction
Adding two numbers is one of the fundamental operations in programming. This guide will walk you through writing a simple Go program that prompts the user to enter two numbers, adds them, and displays the result.
Problem Statement
Create a Go program that:
- Prompts the user to enter two numbers.
- Adds the two numbers.
- Displays the sum of the two numbers.
Example:
- Input: 10and20
- Output: Sum: 30
Solution Steps
- Import the fmt Package: Use import "fmt"to include the fmt package for formatted I/O operations.
- Write the Main Function: Define the mainfunction, which is the entry point of every Go program.
- Declare Variables: Declare variables to store the two numbers and their sum.
- Input the Numbers: Use fmt.Scanlnto take input from the user for the two numbers.
- Add the Numbers: Calculate the sum of the two numbers.
- Display the Sum: Use fmt.Printlnto display the sum.
Go Program
package main
import "fmt"
/**
 * Go Program to Add Two Numbers
 * Author: https://www.javaguides.net/
 */
func main() {
    // Step 1: Declare variables to hold the numbers and the sum
    var num1, num2, sum int
    // Step 2: Prompt the user to enter the first number
    fmt.Print("Enter the first number: ")
    fmt.Scanln(&num1)
    // Step 3: Prompt the user to enter the second number
    fmt.Print("Enter the second number: ")
    fmt.Scanln(&num2)
    // Step 4: Calculate the sum of the two numbers
    sum = num1 + num2
    // Step 5: Display the result
    fmt.Println("Sum:", sum)
}
Explanation
Step 1: Declare Variables
- The variables num1,num2, andsumare declared as integers to store the two input numbers and their sum.
Step 2: Input the First Number
- The program prompts the user to enter the first number using fmt.Print. Thefmt.Scanlnfunction reads the input and stores it in the variablenum1.
Step 3: Input the Second Number
- The program prompts the user to enter the second number, which is then stored in the variable num2usingfmt.Scanln.
Step 4: Calculate the Sum
- The sum of the two numbers is calculated by adding num1andnum2, and the result is stored in thesumvariable.
Step 5: Display the Sum
- The calculated sum is displayed to the user using the fmt.Printlnfunction.
Output Example
Example:
Enter the first number: 10
Enter the second number: 20
Sum: 30
Conclusion
This Go program demonstrates how to add two numbers provided by the user and display the result. It covers basic concepts such as taking user input, performing arithmetic operations, and outputting results, making it a useful example for beginners learning Go programming.