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

Source Code:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include<iostream>
using namespace std;

double power(double,int=2);

int main()
{
 int p;
 double n,r;
 cout << "Enter number : ";
 cin >> n;
 cout << "Enter exponent : ";
 cin >> p;
 r = power(n,p);
 cout << "Result is " << r;
 r = power(n);
 cout << "\nResult without passing exponent is " << r;
 
 return 0;
}

double power(double a, int b)
{
 double x = 1;
 for(int i = 1; i <= b; i++)
  x = x * a;
 return x;
}


Post a Comment

 
Top