Java Program to find the cube of a number.
Objective
Write a Java program to calculate the cube of a number.
Algorithm / Approach
- Prompt the user to enter an integer.
- Calculate the cube by multiplying the number by itself three times (
x * x * x). - Store the result and print it.
Test.java
import java.util.Scanner;
class Test {
public static void main(String[] a)
{
Scanner s=new Scanner(System.in);
System.out.print("Enter Num: ");
int x = s.nextInt();
int y = x*x*x;
System.out.print("Cube = "+y);
}
}
Expected Output
Enter Num: 5 Cube = 125
Explanation of the Program
- The user inputs a number which is stored in variable
x. - The cube is calculated by multiplying the number by itself three times:
x * x * x. - The result is stored in variable
yand printed to the user.
Complexity
Time Complexity
O(1)
Space Complexity
O(1)
Common Mistakes
- Multiplying the number by 3 instead of cubing it.
- Integer overflow if the input number is too large.