Assignments » User Defined Function » Set1 » Solution 4

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.

    
#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;
}

Enter number : 5
Enter exponent : 4
Result is 625
Result without passing exponent is 25

 

 

 

 

«back