In this post, you will learn how to Calculate the Power using Recursion in C++.
This lesson will teach you how to Reverse a Sentence Using Recursion, mathematical operators and decision making statement using the C++ Language. Let’s look at the below source code.
How to Calculate the Power using Recursion?
RUN CODE SNIPPETSource Code
#include <iostream> using namespace std; int FindPower(int base, int power) { if (power == 0) return 1; else return (base * FindPower(base, power-1)); } int main() { int base,power; cin>>base>>power; cout<<base<<" raised to the power "<<power<<" is "<<FindPower(base, power); return 0; }
Input
3 5
Output
3 raised to the power 5 is 243
The statements #include<iostream>, using namespace std, int main are the main factors that support the function of the source code.
Now we can look into the working and layout of the code’s function.
- Declare the variables FindPower, base, power as integers. Declare the if statement with the condition
(power == 0)
and return the value 1. - In the else statement return the mathematical expression
base * FindPower(base, power-1)
. - Starting with int main declare the variables base,power as integers.
- Using the cin and the cout statement collect the base and the power from the user and display the answer. The base, the power and the calculated answer is displayed.
Leave a Review