Write a C++ program to find the value of a number raised to its power that demonstrates a function using call by value.
Algorithm to solve the above problem:
1) Start the program.
2) Declare the variables.
3) Get two numbers as input
4) Call the function power to which a copy of the two variables is passed .
5) Inside the function, calculate the value of x raised to power y and store it in p.
6) Return the value of p to the main function.
7) Display the result.
8) Stop the program.
Implementation of the above problem in C++:
#include<iostream>
using namespace std;
int main()
{
int x,y;
double power(int, int);
cout<<"Enter X and Y :"<<endl;
cin>>x>>y;
cout<<x<<" to the power "<<y <<" is "<< power(x,y);
return 0;
}
double power(int x, int y)
{
double p;
p=1.0;
if(y>=0)
{
while(y--)
p=p*x;
}
else
{
while(y++)
p=p/x;
}
return(p);
}
The output of the above program is tested on www.jdoodle.com
Output:
Enter X and Y :
4 3
4 to the power 3 is 64
Thanks
Mukesh Rajput
Post A Comment:
0 comments: