1: The ordinary implementation of the 99 multiplication table is too simple, even a programmer can do it. The implementation is as follows:
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: Use recursion to implement the 99 multiplication table
The code is as follows:
package test.ms;public class MultiTable { public static void main(String args[]) { m(9); } /** * Print out the 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(); } } }
Call the icon recursively:
Each method call will generate a stack frame and push it onto the method stack. When a recursive call is made, the stack frame in the method stack will look similar to the picture above.
It is more intuitive to remove the reference relationship of the stack frame in the method: as shown in the following figure:
The final execution of the corresponding method call is simplified as shown in the figure above. Note that i has been changing and j starts from 1 each time and then increments until it is equal to i.
In this way, after the above picture is popped out of the stack, 99 multiplication tables are obtained:
Summarize:
Comparison of nested for loops and recursion implementation:
The stack is mainly used to store stack frames. Every time a method is executed, a push operation will occur. Therefore, more stack frames are generated when recursion is used. Recursion will affect the memory and consume a lot of memory. However, using a for loop will execute There is a method that pushes the stack frame once, and only one stack frame exists, so it saves memory.
Welcome to give me a thumbs up. Until knocked unconscious.