Here is working code:
#include<iostream>
using namespace std;
int pow(int, int);
int main()
{
int x,p,ans;
cout<<"Enter a number";
cin>>x;
cout<<"Enter the power of the number";
cin>>p;
ans=pow(x, p);
cout<<ans;
return 0;
}
int pow(int x, int p)
{
int a=1,i;
for(i=0;i<=p;i++)
{
a=a*x;
}
return a;
}
You have to pass the local variables into the function instead of defining new ones with the same name. What you are doing should give you warnings about unused variables (x
and p
in main
) and it also invokes undefined behavior in pow
because of ininitialized reads of the variables defined there.
Also your function was wrong. You were just multiplying 1 with a value a bunch of times, which stays 1 forever.
solved Issue in finding power of a number using user defined functions