15,114,127 members
1.00/5 (1 vote)
See more:
So I have this method which works for the first line of finding the sum of the first and last values in and array. Next, I want to use the same method again to find the sum of the values I have just created. For example.

2, 2, 1, 2, 1 -> is my array
3,4,1 -> my method works perfectly to get these values
4,4 -> Now I would I run my method again so that I can get these values.

What I have tried:

for (int i = 0; i < numbers.Length; i++)
{
if (numbers.Length>2)
{
Result(numbers);//method name
}
else { break; }

// Console.WriteLine(numbers[i]);
}
Posted
Updated 4-Oct-21 20:37pm

## Solution 1

If you have written a method that works perfectly for an array.... what about... calling it?

Yes, a method can call itself (look up recursion, but be careful - it can take a while - according to one of the three jokes we have in computer science)!

So something like
C#
```List<int> DoStuff(List<int> input)
{
if (input.Length > 2)
{
List<int> next = ... // Do you calculation for one level here
return DoStuff(next);
}

return input;
}```
PIEBALDconsult 5-Oct-21 11:40am

With tail recursion it's best just not to write it recursively.
lmoelleb 5-Oct-21 13:13pm

Why?