In this example, you’ll learn to reverse a given sentence using a recursive loop in C#.
In the following program, we’ve a recursive function reverse()
.
On each iteration, we add (concatenate) the result of next reverse()
function to the first character of sentence using sentence[0]
.
The recursive call must be before the sentence[0]
, because that way the last characters will start adding to the left hand side. If you reverse the order, you’ll end up with the original sentence.
In the end, we end up with an empty sentence and reverse()
returns the reversed sentence.
C# Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | public static String reverse(String sentence) { if (sentence == "") { return sentence; } return reverse(sentence.Substring(1)) + sentence[0]; } static void Main(string[] args) { Console.Write(" Sentence : "); String sentence = Console.ReadLine(); String reversed = reverse(sentence); Console.WriteLine(" The reversed sentence is: " + reversed); Console.ReadKey(); } |
When you run the program, the output will be: