Raising a number n to a power p is the same as multiplying n by itself p times. Write a function called power ( ) that takes a double value for n and an int value for p, and returns the result as the double value. Use a default argument of 2 for p, so that if this argument is omitted, the number will be squared. Write a main ( ) function that gets values from the user to test this function.


Implementation of the above problem:
#include<iostream.h>
#include<conio.h>
double power(double n,int p=2);
int main()
{
double n,r;
int p;
char c;
clrscr();
cout<<"enter the number:";
cin>>n;
do
{
cout<<"do you want to enter power(y/n)?:";
cin>>c;
if(c=='y')
{
cout<<"enter the power to be raised:";
cin>>p;
r=power(n,p);
}
else
{
if(c=='n')
{
p=2;
r=power(n);
}
else

cout<<"invalid choice\n";
}
}
while(c!='y'&&c!='n');
cout<<n<<"^"<<p<<"("<<n<<" raised to the power "<<p<<")="<<r;
getch();
return 0;
}
double power(double n,int p)
{
double r=1;
int i;
if(p<0)
r=1/power(n,-p);
else
for(i=1;i<=p;i++)
r=r*n;

return(r);
}


Thanks
Mukesh Rajput
Mukesh Rajput

Mukesh Rajput

I am a Computer Engineer, a small amount of the programming tips as it’s my hobby, I love to travel and meet people so little about travel, a fashion lover and love to eat food, I am investing a good time to keep the body fit so little about fitness also..

Post A Comment:

0 comments: