Thursday, September 6, 2012

Homework 2

Write a recursive function that takes a floating point number A and an integer N, and returns A to the N-th power. Your program should prompt the user for the values of A and N, in that order, then print the result. Like this:

enter real number: 5.0
enter exponent: 3
answer: 125.0
 
Solution: 
import java.util.Scanner; 

class Power
{
  public static void main ( String[] args )
  {
   float A, R;
   int N;
   
   // Create a scanner to read from keyboard
   Scanner scanner = new Scanner (System.in);
   
   System.out.println("enter real number: ");
   A = scanner.nextFloat();
   System.out.println("enter exponent: ");
   N = scanner.nextInt();
   R = pow(A, N);
   System.out.println("answer: " + R);  
  }  
  
 static float pow(float a, int n) 
 { 
   // Base Cases: 
   if (n == 0)
  return 1;
   else if (n == 1)
    return a;
   // Recursive Case:  
   else 
  return a * pow(a, n-1);     
 }  
}