Introduction
Finding the cube of a number involves multiplying the number by itself twice (i.e., raising the number to the power of 3). In Go, you can calculate the cube of a number using simple arithmetic operations. This guide will walk you through writing a Go program that calculates the cube of a user-provided number.
Problem Statement
Create a Go program that:
- Prompts the user to enter a number.
- Calculates the cube of the given number.
- Displays the result.
Example:
- Input:
3 - Output:
"The cube of 3 is 27"
Solution Steps
- Input the Number: Use
fmt.Scanln()to take a number as input from the user. - Calculate the Cube: Multiply the number by itself twice to calculate the cube.
- Display the Result: Use
fmt.Println()to display the calculated cube.
Go Program
package main
import (
"fmt"
)
func main() {
// Step 1: Declare a variable to store the number
var number int
// Step 2: Prompt the user to enter the number
fmt.Print("Enter an integer number: ")
fmt.Scanln(&number)
// Step 3: Calculate the cube of the number
cube := number * number * number
// Step 4: Display the result
fmt.Printf("The cube of %d is %d\n", number, cube)
}
Explanation
Step 1: Declare a Variable
- A variable
numberis declared to store the integer input provided by the user.
Step 2: Input the Number
- The program prompts the user to enter an integer number using
fmt.Scanln().
Step 3: Calculate the Cube
- The cube of the number is calculated by multiplying the number by itself twice:
number * number * number. The result is stored in the variablecube.
Step 4: Display the Result
- The program displays the result using
fmt.Printf(), showing the original number and its cube.
Output Example
Example 1:
Enter an integer number: 3
The cube of 3 is 27
Example 2:
Enter an integer number: 5
The cube of 5 is 125
Example 3:
Enter an integer number: -4
The cube of -4 is -64
Conclusion
This Go program demonstrates how to calculate the cube of an integer by multiplying the number by itself twice. The program handles both positive and negative numbers, providing a straightforward way to compute the cube of any integer. Understanding how to perform basic arithmetic operations in Go is essential for solving many programming problems.