Go Program to Calculate the Area of a Rectangle

1. Introduction

Computing the area of a rectangle is fundamental in various practical applications, such as architecture, design, and spatial planning. In this guide, we will walk through the development of a Go program that calculates the area of a rectangle given its length and width.

2. Program Overview

Our Go program is designed to:

1. Ask the user to input the length and width of the rectangle.

2. Compute the area by multiplying the length by the width.

3. Display the calculated area to the user.

3. Code Program

// Our Go program commences with the declaration of the main package.
package main

// We incorporate the fmt package for managing input and output functionalities.
import "fmt"

// Function to compute the area of the rectangle.
func rectangleArea(length, width float64) float64 {
    return length * width
}

// The program's core functionality resides within the main function.
func main() {
    var length, width float64

    // Prompting the user to provide the rectangle's dimensions.
    fmt.Print("Enter the length of the rectangle: ")
    fmt.Scan(&length)
    fmt.Print("Enter the width of the rectangle: ")
    fmt.Scan(&width)

    // Displaying the computed area.
    fmt.Printf("The area of the rectangle with length %.2f and width %.2f is: %.2f\n", length, width, rectangleArea(length, width))
}

Output:

Assuming the user provides a length of 5 and a width of 10, the program's output will state:
The area of the rectangle with length 5.00 and width 10.00 is: 50.00

4. Step By Step Explanation

1. Package and Import Statements: The expedition starts with the package main declaration, which demarcates the entry point of our program. To facilitate I/O operations, we employ the fmt package.

2. Area Calculation Function: The rectangleArea function is concise and calculates the area of the rectangle by multiplying its length and width.

3. User Input & Result Display: Two floating-point variables, length and width, store the user's input. The user is then prompted to supply the rectangle's dimensions. After obtaining the necessary inputs, the program computes and displays the rectangle's area using the rectangleArea function.

Comments