Create a function power() to raise a number m to power n, the function takes a double value for m and int value for n, and returns the result correctly. Use the default value of 2 for n to make the function calculate squares when this argument is omitted.
Write a main that gets the values of m and n from the user to test the function.
As per the definition, this problem is a good one to understand the concept of default arguments in C++.
First, define a power() function with return type as double and it also accepts two arguments, first argument is of double data type and another one is of integer type as per the given program definition. Now, to make the second argument as default argument assign it value 2. The function signature should look like following:
double power(double m, int n = 2);
In the function definition, declare a variable res with initial value 1, iterate a loop in order to calculate the power and store the result in res variable. Finally, return the value stored in res variable.
Tutorial 📺
Code 💻
#include<iostream.h>
#include<conio.h>
double power(double m, int n = 2)
{
int res=1;
for(; n > 0; n--)
res = m * res; // res *= m;
return res;
}
void main()
{
double m = 0;
int n = 0;
clrscr();
cout << "Please enter the value of m: ";
cin >> m;
cout << "\nPlease enter the power : ";
cin >> n;
cout << m << " to power " << n << " is: " << power(m,n);
getch();
}
Output 😃
Example 1
Please enter the value of m: 2
Please enter the power : 3
2 to power 3 is: 8
Example 2
Let’s take another example, if we do not accept the value of n and call the function by passing only one argument (the value of m).
Imagine, we called the function with following argument:
cout << power(4);
Above function call will still work and here the value of n will be considered 2 which is the default value (of the argument).
Finally it will return the value as 16.
Comments