Go Program To Calculate Cube of a Number

In this post we will learn how to calculate cube of a number using Go Programming language

Hello coders, in this post we will learn how to calculate cube of a number using Go Programming language.

Go Program To Calculate Cube of a Number

A Cube Number is a number multiplied by itself 3 times. For Example: 8 is a cube number because it's 2 x 2 x 2, this is also written as 2^3.

A cube number can also be called a number cubed.

So, without further delay, let's begin the tutorial.

Table Of Contents 👊

Go Program To Calculate Cube of a Number

package main
import "fmt"

func main(){
  var num int 
  
  // Asking for Input
  fmt.Print("Enter a number: ")
  fmt.Scan(&num)
  
  cube := num * num * num
  fmt.Println("The Cube of the Number is", cube)
}

Output

Enter a number: 8
The Cube of the Number is 512

How Does This Program Work ?

  var num int 

In this program, we have declared an int data type variable names an num.

  // Asking for Input
  fmt.Print("Enter a number: ")
  fmt.Scan(&num)

Then, the user is asked to enter an integer. This value will get stored in num named variable.

  cube := num * num * num
  fmt.Println("The Cube of the Number is", cube)

Now, we get the cube of the number by multiplying the number by itself three times. And then, the cube is displayed to the screen using fmt.Println() function.

Some of the used terms in this program are as follows:- 

package main - packages are a collection of Go source files that reside in the same directory. The line package main specifies that this file belongs to the main package.

Every Executable Go Application must contain the main function.

fmt.Println() - The fmt.Println() function in Go language is used to display output.

fmt.Scan() - The fmt.PrintScan() function is used to take input from the user in Go Programming language.

:= - The := syntax is shorthand for declaring and initializing a variable.

// - Used for Commenting in Go  

Go Program To Calculate Cube of a Number Using Functions

package main
import "fmt"

func cubeNumber(n int) int {
  return n * n * n
}

func main(){
  var num int
  
  // Asking for Input
  fmt.Print("Enter the number: ")
  fmt.Scan(&num)
  
  cube := cubeNumber(num)
  fmt.Println("The Cube Root is", cube)
}

Output

Enter the number: 18
The Cube Root is 5832
func cubeNumber(n int) int {
  return n * n * n
}

In this program, we have declared a user defined function named as cubeNumber which returns the cube of the number.

Conclusion

I hope after reading this post, you clearly understood how to calculate cube of a number using Go Programming language.

If you have any doubt regarding the topic, let us know in the comment section.

Sloth Coders is a Learning Platform for Coders, Programmers and Developers to learn from the basics to advance of Coding of different langauges(python, Java, Javascript and many more).

إرسال تعليق