Java Recursive Method
I. Meaning
A recursive algorithm is an algorithm that calls itself directly or indirectly. In computer programming, recursive algorithms are very effective in solving a large variety of problems. They often make the description of algorithms concise and easy to understand.
Ii. Example
99 multiplication table example
1: ordinary realization 99 multiplication table is too simple, is a programmer will, the implementation is as follows:
123456789101112131415 |
package test.ms; public class Test99 { public static void main(String[] args) { for ( int i= 1 ; i<= 9 ;i++){ for ( int j= 1 ; j<=i; j++){ System.out.print(j+ " * " +i+ " = " +(i*j) + " " ); } System.out.println(); } } } |
2: Implement 99 multiplication tables recursively
The Code is as follows:
1234567891011121314151617181920212223 |
package test.ms; public class MultiTable { public static void main(String args[]) { m( 9 ); } /** * Print the 9-9 multiplication table * @param i */ public static void m( int i) { if (i == 1 ) { System.out.println( "1*1=1 " ); } else { m(i - 1 ); for ( int j = 1 ; j <= i; j++) { System.out.print(j + "*" + i + "=" + j * i + " " ); } System.out.println(); } } } |
Recursive call illustration:
Each method call generates a stack frame, which is pushed to the method stack. When recursive calling is performed, the stack frame diagrams in the method Stack are similar.
Removing the reference relationship of stack frames in the method is more intuitive: As shown in:
The final execution of the corresponding method call is simplified, as shown in. Note that I is always changing. j starts from 1 and then increments to be equal to I.
In this way, the 99 multiplication table is obtained after the stack is output in sequence:
Summary:
Comparison between nested for loops and recursive implementations:
Stack is mainly used to store stack frames. Each method executed will have a stack operation. Therefore, many stack frames are generated when recursion is used, and Recursion will affect the memory, memory consumption is very high, and a method is executed using the for loop, which is pushed to the stack frame once and only one stack frame exists, which saves memory.