Question

**Programming Langauge: Java**

•Given non-negative integers x and n, x taken to the nth power can be defined as:

•x to the 0th power is 1

•x to the nth power can be obtained by multiplying x to the n-1th power with x

•Write a long-valued method named power that accepts an two int parameters x and n (in that order) and recursively calculates and returns the value of x taken to the n'th power

•For example, to find x4

•x4 = x * x3

•x3 = x * x2

•x2 = x * x1

•x1 = x

•x0 = 1

•Next write the code to compute powers using iteration

Answer #1

I have uploaded the Images of the code, Typed code and Output of the Code. I have provided explanation using comments (read them for better understanding).

**Images of the Code:**

**Note: If the below code is missing indentation please refer
code Images**

**Typed Code:**

// importing required packages

import java.util.*;

// A Main class

public class Main

{

// A long valued method named as power

// with input parameters x and n (Non negative numbers)

static long power(int x, int n)

{

// checking whether x or n are negative

if( x<0 || n<0)

{

// returning 0

return 0;

}

else

{

// if n is 0

if(n == 0)

{

// returning value 1

return 1;

}

else

{

// calling method power with parameters x,n-1

// and returning x and power(x,n-1)

return x*power(x, n-1);

}

}

}

// Main Method

public static void main(String[] args)

{

// local variables

int x=5, n=3;

// calling the Method power and printing the returned
value

System.out.print(x + "^" + n + " =
" + power(x,n));

System.out.println(" (using
recursion method power)");

// A variable to store power
value

long power=1;

// printing informative
message

System.out.print(x + "^" + n + " =
");

// calculating power using
iterations

// A while loop that runs until n
becomes 0

while(n>0)

{

// multiplying value of x with
power

power = power * x;

// decrementing n

n--;

}

// printing calculated power

System.out.print(power);

// printing the message

System.out.println(" (using
iteration)");

}

}

**//code ended here**

**Output:**

If You Have Any Doubts. Please Ask Using Comments.

Have A Great Day!

ADVERTISEMENT

Get Answers For Free

Most questions answered within 1 hours.

ADVERTISEMENT

asked 8 minutes ago

asked 12 minutes ago

asked 30 minutes ago

asked 33 minutes ago

asked 36 minutes ago

asked 42 minutes ago

asked 1 hour ago

asked 1 hour ago

asked 1 hour ago

asked 1 hour ago

asked 1 hour ago

asked 2 hours ago