function with arguments



Raising a number n to a power p is 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 returns the result as double value. Use a default argument of 2 for p so that if this argument is omitted the number will be squared. Write the main function that gets the values from user the user to test the function.


PROGRAM



#include<iostream.h>
#include<conio.h>
double power(double n,int p=2)
{
double x=1.0; int i;
for (i=0;i<p;i++)
x*=n; return x;
}
void main()
{
double n,res; int p;
char ch; clrscr();
cout<<"Enter a number to be raised to a power: "; cin>>n;
cout<<"Do you want to enter the power (Y/N): "; cin>>ch;
if ((ch=='y')||(ch=='Y'))
{

cout<<"Enter the power to which the number "<<n<<" is to be raised: "; 
cin>>p;
res=power(n,p);

}
else

res=power(n);

cout<<"The result is: "<<res; getch();
}
 


OUTPUT




Enter a number to be raised to a power: 5 Do you want to enter the power (Y/N): Y
Enter the power to which the number 5 is to be raised: 3

No comments:

Post a Comment

Comment Here