Go Program to Multiply Two Numbers

1. Introduction

In this post, we'll learn how to create a Go program to multiply two numbers entered by the user.

2. Program Overview

Our program in Golang will have the following objectives:

1. Prompt the user to provide two numbers.

2. Calculate the product of the given numbers.

3. Exhibit the computed product to the user.

3. Code Program

// The main package is the common starting point for a Go application.
package main

// The fmt package is imported for input and output operations.
import "fmt"

// Our program begins execution with the main function.
func main() {
    // We declare three float64 variables to hold the input numbers and their product.
    var num1, num2, product float64

    // We ask the user to input the first number, storing it in num1.
    fmt.Print("Enter the first number: ")
    fmt.Scan(&num1)

    // Similarly, we prompt for the second number, saving it to num2.
    fmt.Print("Enter the second number: ")
    fmt.Scan(&num2)

    // Multiplication of num1 and num2 is performed, and the result is stored in product.
    product = num1 * num2

    // The computed product is then displayed in a formatted manner.
    fmt.Printf("The product of %v and %v is: %v\n", num1, num2, product)
}

Output:

Assuming the user provides the numbers 6 and 7, the program's output would be:
The product of 6 and 7 is: 42

4. Step By Step Explanation

1. Package and Import Statements: We initiate with package main, designating our program's entry point. Subsequently, the fmt package is imported to allow input-output functionalities.

2. Variable Declarations: Utilizing the var keyword, we have initialized three variables of type float64 that will hold the two numbers and their resulting product.

3. Acquiring User Input: The fmt.Print function offers a prompt to the user and the fmt.Scan function secures the user's input into the corresponding variable.

4. Multiplication Operation: Using the * operator, the numbers num1 and num2 are multiplied, and the product is preserved in the product variable.

5. Output Display: At the end, we employ fmt.Printf to share the multiplication result with the user in a structured format.

Comments