Click here to Skip to main content
15,114,127 members
Please Sign up or sign in to vote.
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.

Please help me.

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

1 solution

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;
}
   
Comments
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?

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900