Go Program to Add Two Numbers

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: 10 and 20
  • Output: Sum: 30

Solution Steps

  1. Import the fmt Package: Use import "fmt" to include the fmt package for formatted I/O operations.
  2. Write the Main Function: Define the main function, which is the entry point of every Go program.
  3. Declare Variables: Declare variables to store the two numbers and their sum.
  4. Input the Numbers: Use fmt.Scanln to take input from the user for the two numbers.
  5. Add the Numbers: Calculate the sum of the two numbers.
  6. Display the Sum: Use fmt.Println to 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, and sum are 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. The fmt.Scanln function reads the input and stores it in the variable num1.

Step 3: Input the Second Number

  • The program prompts the user to enter the second number, which is then stored in the variable num2 using fmt.Scanln.

Step 4: Calculate the Sum

  • The sum of the two numbers is calculated by adding num1 and num2, and the result is stored in the sum variable.

Step 5: Display the Sum

  • The calculated sum is displayed to the user using the fmt.Println function.

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.

Leave a Comment

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

Scroll to Top