Learn C# · lesson 51 of 61 · about 9 minutes
Recursion on Arrays and Strings
Handle one item, then let a recursive call handle the rest.
What you'll learn
- Recurse over an array with an index
- Recurse over a string
- Choose the right stopping point
Replaying the boss fight
Rested, the hero tells the blacksmith about the boss fight, blow by blow, and the battle sums it up: Replay: 4 blows, 50 damage, hardest 18. Two recursive methods do the work on an array of the boss hits: TotalDamage adds blow i to the total of the blows after it, and HardestBlow keeps the bigger of blow i and the hardest of the blows after it. Both pass the array and an index that moves one place on each call. bossHits.ToArray() turns the list into an array first.
An index instead of a copy
Copying an array on every call would be slow, so recursive methods pass the array and an index that says where to start.
The total from index i onwards is a[i] plus the total from i + 1. When i reaches a.Length, there's nothing left, so the total is 0.
Adding up an array
int[] nums = { 4, 1, 5, 2 };
Console.WriteLine(Total(nums, 0));
static int Total(int[] a, int i)
{
if (i == a.Length) return 0;
return a[i] + Total(a, i + 1);
}Output
12Strings work the same way
s[0] is the first character and s[1..] is the rest (a range: from index 1 to the end). To reverse a string, reverse the rest first, then add the first character on the end. The base case is the empty string.
Reversing text
Console.WriteLine(Reverse("phoebe"));
static string Reverse(string s)
{
if (s.Length == 0) return "";
return Reverse(s[1..]) + s[0];
}Output
ebeohpA different base case for the hardest
Not every question has an answer for no items at all. The total of no blows is 0, but there's no hardest among none. So HardestBlow stops at the last blow, i == blows.Length - 1, which is the hardest of itself, and the battle only calls it when at least one blow landed.
Tip
For flat arrays a loop or LINQ is usually simpler. Recursion shines on data inside data, like the parts of the dragon trap in this unit's project.
Now try it yourself
This lesson is free in Codiqo, with 9 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.