1/17/2017

Java Program to Find Square and Cube of a Number (N^1, N^2, N^3)

Problem:- Java Program to Calculate the Power of a Number or Given a cube of size n*n*n or Java program to find Square, Cube and Square Root of an integer or How to square a number in Java or Java Program to print square of numbers or Simple java Programmes: find Square and cube of a Number or java program to find square and cube of a number or Square and Cube Number Program in Java or Calculating Squares and Cubes in a table or Calculate Cube And Square Program in Java or Write a Java program to read integer (N) and print first three powers (N^1, N^2, N^3) example if user enters a 5 from keyboard then output should be 5, 25, 125 Means power of number in 1, 2, 3.


Logic:- For this problem We need to multiply number or we can use power function for that take an example for better understood this problem take a Number 5 as input and multiply with the same number again like 5 * 5 for cube we need to again multiply with the same number like 5 * 5 * 5 or we can use power function.

Power Function Syntax:- for given example x^y.

pow(x, y)

also, define the data type of x or y and here x is a number and y is the power of x.

See Also:- C Program To Read Integer (N) And Print First Three Powers (N^1, N^2, N^3)

Method 1:- Simple Without Using Power Function


import java.util.Scanner;
import java.lang.*;

/* Program By Ghanendra Yadav
   Visit http://www.programmingwithbasics.com
*/

public class threenum
{
    public static void main(String args[])
    {
        int num,a,b,c; 
        Scanner sc = new Scanner(System.in);
 
        System.out.print("Enter The Number :\n\n");
        num = sc.nextInt();
 
  a=num;
  b=num*num;
  c=num*num*num;

  System.out.println("\nOutput Is = " + a + " ,"+ b +" ,"+ c +"\n\n"); 
 }
} 

Method 2:- Using Power Function

import java.util.Scanner;
import java.lang.*;

/* Program By Ghanendra Yadav
   Visit http://www.programmingwithbasics.com
*/

public class threenum1
{
    public static void main(String args[])
    {
        int num;
  double a,b,c; 
    
  Scanner sc = new Scanner(System.in);
 
        System.out.print("Enter The Number :\n\n");
        num = sc.nextInt();

  a=Math.pow(num,1);
  b=Math.pow(num,2);
  c=Math.pow(num,3);

  System.out.println("\nOutput Is = " + a + " ,"+ b +" ,"+ c +"\n\n"); 
 }
}

See Also:- C++ Program To Read Integer (N) And Print First Three Powers (N^1, N^2, N^3)

Output:-


Java Program to Find Square and Cube of a Number (N^1, N^2, N^3)
Java Program to Find Square and Cube of a Number (N^1, N^2, N^3)

You May Also See


1. Java Program To Calculate Factorial Of A Given Number

2. Java Program For Calculate Percentage Of 5 Subjects

3. C++ Program For Draw A Perfect Christmas Tree

4. C++ Program For ROUND ROBIN Scheduling Algorithm In Linux

5. C++ Program For (SJF) SHORTEST JOB FIRST Scheduling Algorithm In Linux

No comments:

Post a Comment