"The best way to cheer yourself up is to try to cheer somebody else up." Mark Twain

Wednesday, March 10, 2010

Raising a number n to a power p is the same as multiplying n by itself p times. Write a overloaded function power() having two versions for it. The first version takes double n and int p and returns a double value. Another version takes takes int n and int p returning int value. Use a default value of 2 for p in case p is omitted in the function call.


#include<iostream.h>
#include<conio.h>
                              
//first function
int power(int n, int p=2)
{
int res  = 1;
for(int i = 1; i < = p ; i++)
res = res * n;
                      
return res;
}


//second function
double power(double n, int p = 2)
{
double res = 1.0;
                   
for(int i = 1; i < = p ; i++)
res = res * n;
                         
return res;
}

void main()
{
int value, powr, result;
/* Calculate the square of an integer */
cout<< "\n Enter a value (any integer ) to find it's square:";
cin>> value;
// first function will be called
result = power(value);
cout<< "The square of " << value << " is " << result;
                                                                                 /* Calculate n to the power m */                                        
cout<< "\n Enter a value (any integer) :";
cin>> value;
cout<< "\n Enter its power (any integer) :";
cin>> powr;
// first function will be called
                                         

result = power(value, powr);
cout<< "\n The " << value << " to the power of " << powr <<" is " << result;

int p;
float val, r;

/* Calculate n to the power of m */
cout<< "\n Enter a value :";
cin>> val;
cout<< "\n Enter its power ( integer):";
cin>> p;
//second function is called
                                       
 r = power(val, p);
cout<< "\n The " << val << " to the power of " << p <<" is " << r;
                        
/* Calculate the square of a decimal number */
cout<< "\n Enter a value :";
cin>> val;
// second function will be called
r = power(val);
cout<< "\n The square of " << val < <" = " << r;
getch();
              
}

1 comment:

C makes it easy to shoot yourself in the foot; C++ makes it harder, but when you do it blows your whole leg off.
Now Playing: Ballade Pour Adeline

About Me

My photo
I m an IT lecturer of a college. I love social-work. I want to do something beneficial for society before dying , that can promote our society, to some extent.