Go Program to Subtract Two Numbers

1. Introduction

Subtraction is one of the elementary arithmetic operations, and when diving into a new programming language, it's beneficial to familiarize oneself with its implementation. In this post, we'll explore how to create a program in Go (also referred to as Golang) that subtracts two numbers provided by the user.

2. Program Overview

Our Golang program's primary goals are to:

1. Prompt the user to input two numbers.

2. Compute the difference between the two numbers.

3. Present the result to the user.

3. Code Program

// The main package declaration indicates the starting point of our application.
package main

// We'll import the fmt package to handle formatted input and output operations.
import "fmt"

// The main function, where the program begins its execution.
func main() {
    // Declaration of three variables of type float64 to hold our numbers and the result.
    var num1, num2, difference float64

    // Prompting the user for the first number and capturing it in the num1 variable.
    fmt.Print("Enter the first number: ")

    // Prompting for the second number, and storing it in the num2 variable.
    fmt.Print("Enter the second number: ")

    // Calculating the difference between num1 and num2.
    difference = num1 - num2

    // Displaying the result with a formatted message.
    fmt.Printf("The difference between %v and %v is: %v\n", num1, num2, difference)


Enter the first number: 20
Enter the second number: 10
The difference between 20 and 10 is: 10

4. Step By Step Explanation

1. Package and Import Declarations: The program starts with package main, marking the program's entry point. Then, we import the fmt package for I/O operations.

2. Variable Initialization: We've declared three float64 variables using the var keyword to hold the two numbers and their difference.

3. Capturing User Input: The fmt.Print function provides a message to prompt the user, and fmt.Scan captures and stores the user's response in the appropriate variable.

4. Subtraction Operation: The subtraction operation is carried out using the - operator, and the result is stored in the difference variable.

5. Displaying the Outcome: Finally, we use fmt.Printf to format and present the result to the user.