# Java Programming | Square and cube of each digit in number

Introduction

This is a tutorial for square and cube of each digit in a number. Two programs are given below that explains it in detail. The program is not extendable. Go enjoy the program. Lets begin…….

Program for square of each digit in number in java.

``````
//import Scanner as we require it.
import java.util.Scanner;

// the name of our class its public
public class SquareDigit {
//void main
public static void main (String[] args)
{
//declare int
int no,m,s;

//Declare input as scanner
Scanner input = new Scanner(System.in);

//Take input
System.out.println("Enter Number :");
no = input.nextInt();

while(no>0)
{
m=no%10;
s = m*m;
System.out.println("Square of "+m+" is "+s);
no=no/10;
}
}
}
``````

Output

Enter Number :
1234
Square of 4 is 16
Square of 3 is 9
Square of 2 is 4
Square of 1 is 1

Program for cube of each digit in number in java.

[code language=”java”]
//import Scanner as we require it.
import java.util.Scanner;

// the name of our class its public
public class CubeDigit {
//void main
public static void main (String[] args)
{
//declare int
int no,m,c;

//Declare input as scanner
Scanner input = new Scanner(System.in);

//Take input
System.out.println(“Enter Number :”);
no = input.nextInt();

while(no>0)
{
m=no%10;
c = m*m*m;
System.out.println(“Cube of “+m+” is “+c);
no=no/10;
}
}
}
[/code]

Output

Enter Number :
1234
Cube of 4 is 64
Cube of 3 is 27
Cube of 2 is 8
Cube of 1 is 1

How does it work

1. You enter the number.
2. The last digit of numbers is separated.
3. The square or cube is calculated.
4. The square or cube is printed.

Extending it

The program cannot be extended.

Explanation.

1. Import the Scanner.
2. Declare the class as public
3. Add the void main function
4. Add system.out.println() function with the message to enter number.
5. Declare input as Scanner.
6. Take the inputs and save it in variables.
7. Add a loop and calculate cube of each digit
8. Add system.out.println() function to print the cube.

At the end.

You learnt creating the Java program for Square and cube of each digit in number. So now enjoy the program.

Please comment on the post and share it.
And like it if you liked.

Sharing options: