Popular Tutorials
Start Learning C++Certification Courses
Created with over a decade of experience and thousands of feedback.
Python online compiler
JavaScript online compiler
SQL online compiler
Java online compiler
HTML online compiler
C online compiler
C++ online compiler
C# online compiler
PHP online compiler
Swift online compiler
Kotlin online compiler
TypeScript online compiler
Go online compiler
Rust online compiler
Scala online compiler
Dart online compiler
R online compiler
Ruby online compiler
C++ Program to Calculate Power Using Recursion
This program calculates the power of a number using recursion where base and exponent is entered by the user.
To understand this example, you should have the knowledge of the following C++ programming topics:
Example: Program to Computer Power Using Recursion
#include <iostream>
using namespace std;
int calculatePower(int, int);
int main()
{
int base, powerRaised, result;
cout << "Enter base number: ";
cin >> base;
cout << "Enter power number(positive integer): ";
cin >> powerRaised;
result = calculatePower(base, powerRaised);
cout << base << "^" << powerRaised << " = " << result;
return 0;
}
int calculatePower(int base, int powerRaised)
{
if (powerRaised != 0)
return (base*calculatePower(base, powerRaised-1));
else
return 1;
}
Output
Enter base number: 3 Enter power number(positive integer): 4 3^4 = 81
This technique can only calculate power if the exponent is a positive integer.
To find power of any number, you can use the pow() function.
result = pow(base, exponent);
Also Read:
Did you find this article helpful?