Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

power.cpp : Write a program that computes integer powers of floating-point numbe

ID: 3887812 • Letter: P

Question

power.cpp: Write a program that computes integer powers of floating-point numbers in two ways—recursively and interatively. You may not use the math library for this assignment.

Your code should implement the following two methods.

You must implement these function prototypes exactly as entered below. Your code must match the return type, argument types, and function name exactly (case-sensitive):

The following two methods take as input a double-precision floating point number and an exponent to raise it to and return the value of the base raised to the exponent.

– double recursivePow(double base, int exponent);
The important feature of this method is that it must solve this problem recursively.

– double iterativePow(double base, int exponent);
The important feature of this method is that it must solve this problem iteratively.

Explanation / Answer

#include <iostream>
using namespace std;

float power(float x, unsigned int y)
{
if (y == 0)
return 1;
else if (y%2 == 0)
return power(x, y/2)*power(x, y/2);
else
return x*power(x, y/2)*power(x, y/2);
}

/* Program to test function power */
int main()
{
float x = 0;
unsigned int y = 0;
cout<<"enter the Integer and Power";
cin>>x>>y;

cout<< power(x, y);
return 0;
}

output:

enter the Integer and Power:

2.12

3

9.52813

Iterative method:

#include <iostream>

using namespace std;

int main()

{

float in;
unsigned int y,i;
float total;
total = 1;
cout << "Enter a number: ";
cin >> in;
cout << " Raise first number to the power of: ";
cin >> y;
total=in;
for(i=1; i<y; i++)
{
total=total*in;
}
cout <<' '<< in << ' ' << "to the" << ' ' << y << ' ' << "power is: " << total << ' ';
return(0);

}

output:

Enter a number:2.12

Raise first number to the power of:3

2.12 to the 3 power is: 9.52813