C
C#3y ago
Lounder

Simple Recursion [Answered]

How can I make a recursive method return false when one or more of the iterations have returned false but the top recursion has returned true?
-true
-true
-false // method should return false
-true
-true
-false // method should return false
Example with code:
static void Main(string[] args)
{
/*
8. Write a program in C# Sharp to check whether a given string is Palindrome or not using recursion. Go to the editor
Test Data :
Input a string : RADAR
Expected Output :
The string is Palindrome.
*/

Console.WriteLine(ReverseLetters("RADAR"));
}

private static bool ReverseLetters(string word)
{
if (word.Length > 1 && word[0] == word[word.Length - 1])
{
ReverseLetters(word.Substring(1, word.Length - 2));
return true;
}

return false;
}
static void Main(string[] args)
{
/*
8. Write a program in C# Sharp to check whether a given string is Palindrome or not using recursion. Go to the editor
Test Data :
Input a string : RADAR
Expected Output :
The string is Palindrome.
*/

Console.WriteLine(ReverseLetters("RADAR"));
}

private static bool ReverseLetters(string word)
{
if (word.Length > 1 && word[0] == word[word.Length - 1])
{
ReverseLetters(word.Substring(1, word.Length - 2));
return true;
}

return false;
}
2 Replies
Lounder
LounderOP3y ago
RADAR -> True (correct) XADAR -> False (correct) RXDAR -> True (incorrect because the first recursion returns true but the next ones return false) Which value is returned to the root method in the WriteLine? The bottommost or the topmost Thank you
Accord
Accord3y ago
✅ This post has been marked as answered!
Want results from more Discord servers?
Add your server