Recursion calls itself repeatedly until it has reached a base case. For the most part it can do anything that can be achieved through loops and iteration, however can complete it in far less code. Below is a collection of all recursion that I have completed, and some I am still working on.
Code 1.
Create a recursive function that will take an input of X and n, and return the value of X to the power of n
//power.h
#ifndef _POWER_H_
#define _POWER_H_
class power
{
public:
int powers(int, int);
private:
};
#endif
//power.cpp
#include "power.h"
using namespace std;
int power::powers(int x, int n)
{
if(n <= 1)
{
return x;
}else {
return x * powers(x, n-1);
}
};
//main.cpp
#include "power.h"
#include <iostream>
using namespace std;
int main()
{
power calc;
power another;
cout << calc.powers(2,3) << endl;
cout << another.powers(7,2) << endl;
return 0;
}
In case you have forgotten how to run a class set of c++ files type into the terminal “g++ power.cpp main.cpp -Wall”
output
8
49
More code will added as it is completed 🙂