Coding Lab - TechOnTechnology

Java recursive program to compute a Power n. Where ‘a’ and ‘n’ are integers.




import java.io.*;
class apowern{
    public static void main(String[] args) throws IOException{
        DataInputStream in=new DataInputStream(System.in);

        System.out.println("\nCALCULATE a POWER n :");
        System.out.print("\nENTER VALUE FOR a : ");       
        double a = Integer.parseInt(in.readLine());
        System.out.print("ENTER VALUE FOR n : ");       
        double n = Integer.parseInt(in.readLine());

        if ( a == 0 && n == 0 )
            {
                System.out.println("\nTHIS OPERATION CAN NOT BE PERFORMED ! ");
            }
        else
            {
                System.out.println("\na POWER n = "+power(a,n));
            }
    }

public static double power(double x, double y) /* Recursive method */
{

    if (x==0)
    {
        return 0;
    }
    else if(y==0)
    {
        return 1;
    }
    else if (y>0)
    {
        return( x* power(x,y-1));
    }
    else
    {
        return ((1/x)*power(x,y+1));
    }
}

}

Name

Email *

Message *