HomeC++C++ program to Calculate the Power using Recursion

C++ program to Calculate the Power using Recursion

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 SNIPPET

Source 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.

  1. Declare the variables FindPower, base, power as integers. Declare the if statement with the condition (power == 0) and return the value 1.
  2. In the else statement return the mathematical expression base * FindPower(base, power-1) .
  3. Starting with int main declare the variables base,power as integers.
  4. 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.

Share:

Leave A Reply

Your email address will not be published. Required fields are marked *

You May Also Like

In this post, you will learn how to Generate Multiplication Table using C++ programming language. This lesson will teach you...
  • C++
  • January 30, 2022
In this post, you will learn how to Display Fibonacci Sequence using C++ programming language. This lesson will teach you...
  • C++
  • January 30, 2022
In this post, you will learn how to Find GCD of two Numbers using C++ programming language. This lesson will...
  • C++
  • January 30, 2022