Chansters
Chansters

Reputation: 141

Is this considered recursion?

I'm very new to programming and would like to know if this code can also be considered a recursion since it calls itself. Also would like to know if this is good practice.

void editArr(int arr[], int arrSize){
int index;

cout << "Enter INDEX: ";
cin >> index;

if(index >= arrSize){
  cout << "INDEX is OUT OF BOUNDS" << endl;
  editArr(arr, arrSize);
}

cout << "Enter VALUE: ";
cin >> arr[index];

cout << "\n[1] Continue || [0] Exit";
cin >> choiceExit;
if(choiceExit == 1)
  editArr(arr, arrSize);

}

Upvotes: 0

Views: 91

Answers (3)

jayjay
jayjay

Reputation: 1047

The function calls itself, it is recursive.

The program will allocate a new stack frame every time the user choses to continue, as this could happen indefinitely, I would say a loop is a better choice here.

As a side note, this function is tail recursive (except when an OOB index is given, then all hell breaks loose), so the compiler may well optimize out allocating the extra stack frame, personally I would not rely on that though.

Upvotes: 1

user7195968
user7195968

Reputation:

It seems it will work. Don't forget to define choiceExit as an integer at the top of the function. Note that it's not the usual way to initialize an array,recursion is a bit "heavy". Also it's important to note that you don't need to put Arraysize as a parameter as size(Arr) will give it. A while loop would be indeed much better. ChoiceExit could be a boolean by the way, as there are only two "cases" possible

Upvotes: 0

πάντα ῥεῖ
πάντα ῥεῖ

Reputation: 1

I'm very new to programming and would like to know if this code can also be considered a recursion since it calls itself.

Yes, that's how recursion is defined. A function calls itself directly or indirectly.

Also would like to know if this is good practice.

In general no. It's better to replace that code with a loop and using a stack (e.g. std::stack). In your case even a simple loop would work fine.

Recursive calls depend on the (limited) intrinsic call stack size, and are prone to overflow the call stack.

Upvotes: 1

Related Questions