Write C++ program to find power of a number using recursion


I have used CodeBlocks compiler for debugging purpose. But you can use any C++ programming language compiler as per your availability.


techstudy.org

HP 15 Core i3 7th gen Laptop(4GB, 1TB HDD, Windows 10) | Rs. 31,490

Introduction

I have used CodeBlocks compiler for debugging purpose. But you can use any C++ programming language compiler as per your availability.


  1. #include <iostream>
  2. #include <math.h>
  3. using namespace std;
  4.  
  5. //function declaration
  6. double Power(double base, int exponent);
  7.  
  8. int main()
  9. {
  10. double base, power;
  11. int exponent;
  12.  
  13. // Inputting base and exponent from user
  14. cout<<"Enter base: ";
  15. cin>>base;
  16. cout<<"Enter exponent: ";
  17. cin>>exponent;
  18.  
  19. // Call Power function
  20. power = Power(base, exponent);
  21.  
  22. //printf("%.2lf ^ %d = %f", base, exponent, power);
  23. cout<<base<< "^"<<exponent<<" = "<<power;
  24.  
  25. return 0;
  26. }
  27.  
  28. /*
  29.   Calculating power of any number.
  30.   Returns base ^ exponent
  31.  */
  32. double Power(double base, int exponent)
  33. {
  34. // Base condition
  35. if(exponent == 0)
  36. return 1;
  37. else if(exponent > 0)
  38. return base * pow(base, exponent - 1);
  39. else
  40. return 1 / pow(base, - exponent);
  41. }

Result

C++ language techstudy.org

     





Related Topics




Popular Posts