arrays - how to avoid a return statement in recursion -


this program printing sum of numbers in array given input parameter. not happen. please let me know mistake , provide me solution explanation.

namespace linkedlists {     class program     {         static void main(string[] args)         {             int[] arr = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 };             int x = sumofnum(arr, 0);             console.writeline(x);             console.readline();         }         public static int sumofnum(int[] arr, int x)         {             int[] arr_new = new int[arr.length - 1];             if (arr.length > 1)             {                 x += arr[arr.length - 1];                 (int = 0; < arr.length - 1; i++)                 {                     arr_new[i] = arr[i];                 }             }              if (arr.length > 1)             {                 sumofnum(arr_new, x);             }              return x;         }     } } 

your question's title "how avoid return statement in recursion", should doing instead of avoiding in recursion scenario.

but not problem code, because nothing described supposed do.

as mentioned in comments, not requires (or recommended) use recursive approach. can done, inefficient , lead stack overflow if have large input array (it needs new stack frame each recursive method call in c#).

to solve recursively, need try , state problem recursive problem, before start trying code it. in pseudo code, input array x of size n:

array_sum(x):     if (x empty)         return 0;     else         return x[0] + array_sum(x[1:n-1]) 

an implementation in c# try avoid allocating new array instance (as opposed 1 of non-functioning parts in code of question doing), , instead keep track of start index input array:

public static array_sum(int startindex, int[] x)  {     // ... } 

Comments

Popular posts from this blog

angularjs - ADAL JS Angular- WebAPI add a new role claim to the token -

php - CakePHP HttpSockets send array of paramms -

node.js - Using Node without global install -