Why this recursion is infinite? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Why this recursion is infinite?

#include <iostream> using namespace std; bool palindromes(char *S, int n, int i){ if (n<=i){ return 1; } else{ if (S[i] == S[n-1]){ return palindromes(S,n--,i++); } else{ return 0;} } } int main() { bool t; int lung; char S[100]; cin.getline(S, 100); lung = cin.gcount() - 1; cout << "start" << endl; t=palindromes(S, lung, 0); if(t==true){ cout<<"the string is palindrome"<<endl; }else{ cout<<"the string isn't palindrome"<<endl; } cout << "end" << endl; }

5th Dec 2018, 11:14 AM
riccardo
3 Answers
+ 6
You are not decreasing `n`. Change `n--` to `--n`, or better `n-1`. By the way a good way to debug recursive programs is to just print all the parameters at the top of the function.
5th Dec 2018, 11:20 AM
Schindlabua
Schindlabua - avatar
+ 6
The first thing I've noticed is that you pass n-- as argument. So basically n will be passed and decreased afterwords. I think --n would be correct. (also ++i, or to be sure simply write n - 1 and i + 1)
5th Dec 2018, 11:20 AM
Aaron Eberhardt
Aaron Eberhardt - avatar
+ 1
perfect, i’ve understood, the problem was on the decreasing argument, like you told me. now the program works, thanks you
5th Dec 2018, 11:56 AM
riccardo