In C++ Design and implement a recursive function that performs the same task as
ID: 3807388 • Letter: I
Question
In C++ Design and implement a recursive function that performs the same task as a loop counter. This function will have a void return type and two parameters. One parameter holds the initial value of the counter variable and is incremented on each recursive call. The other parameter holds a limit, specifying the number of desired iterations plus one. The base case occurs when the counter variable is equal to the limit. In the general case, print out the counter value. Display a message indicating the loop is finished when the base case is reached. Test your function with a simple calling program.
Explanation / Answer
snippet :
#include <iostream>
#include <iomanip>
#include <cstdlib>
using namespace std;
void loop(int num, int num1)
{
if(num <= num1){
cout << "The counter value is :" << num;
cout << endl;
loop(num+1,num1);
}else {
cout << "The base case has reached";
}
}
int main()
{
int num=0, num1, evenSum2;
cout << "Enter a limit for iteration): ";
cin >> num1;
loop(num+1, num1);
return 0;
}
sample output :
Enter a limit for iteration): 5
The counter value is :1
The counter value is :2
The counter value is :3
The counter value is :4
The counter value is :5
The base case has reached