java - Not able to understand this recursion -



java - Not able to understand this recursion -

the input {4,7,3,6,7} , output is:

[81] [40, 41] [21, 19, 22] [11, 10, 9, 13] [4, 7, 3, 6, 7]

the recursive programme have below, have added print statements understand recursion:

import java.util.arrays; public class triangle_array { public static void print(int a[]) { if(a.length==0) return; int n=a.length; int newa[]=new int[n-1]; for(int i=0;i<n-1;i++) { newa[i]=a[i]+a[i+1]; } system.out.println("here1") ; print(newa); system.out.println("here2") ; if(newa.length!=0) system.out.println(arrays.tostring(newa)); } public static void main(string args[]) { int a[]={4,7,3,6,7}; print(a); system.out.println(arrays.tostring(a)); } }

i got output as:

here1 here1 here1 here1 here1 here2 here2 [81] here2 [40, 41] here2 [21, 19, 22] here2 [11, 10, 9, 13] [4, 7, 3, 6, 7]

i not able understand recursion, above here statements, understand print methos beingness called recursively first, , when status fails, returns outside of print , goes line , prints "here2" 2 times , verifies length of newa zero, until point understood, in next iterations how length of newa increment , how below status become true, println statement ?

in general, if there prints in recursive method, prints come before recursive phone call printed in order of increasing recursion depth, , prints come after recursive phone call printed in reverse order.

public static void demorecursion( int n, int depth ) { if ( n <= 0 ) { return; } system.out.println( "before recursive call, depth " + depth ); demorecursion( n - 1, depth + 1 ); system.out.println( "after recursive call, depth " + depth ); }

if phone call method using demorecursion( 3, 1 ) you'll get:

class="lang-none prettyprint-override">before recursive call, depth 1 before recursive call, depth 2 before recursive call, depth 3 after recursive call, depth 3 after recursive call, depth 2 after recursive call, depth 1

so it's not if a increasing in size. it's @ depth 1, have 5 item array, @ depth 2, have 4 item array, @ depth 3, have 3 , on.

so because of reverse printing effect demonstrated above, each depth`s array printed after array of deeper level, shorter.

if had printed array before recursive call, prints have been in decreasing order.

java recursion

Comments

Popular posts from this blog

java Multi query from Mysql using netbeans -

c# - DotNetZip fails with "stream does not support seek operations" -

c++ - StartServiceCtrlDispatcher don't can access 1063 error -