1. The concept of recursion
1. What is recursion?
Recursion is: the process of calling a method by itself.
There are two prerequisites for using recursion:
1. There is an approach and termination condition.
2. Call yourself.
How to implement recursion?
The most important way is: to implement recursion, you need to derive a recursive formula.
The way to think about recursion: think laterally and think according to the recursive formula.
Code execution: vertical execution.
2. Recursion explanation
First look at the following code:
public class TestDemo { public static void func(){ func(); //自己调用自己本身 } public static void main(String[] args) { func(); } }
The code above is a simple recursion.
Let’s take a look at the running results of this code.
Drawing explanation:
For the recursion in the above picture, there is no A condition that tends to terminate, so this function will recurse endlessly. Every time you recurse, memory must be allocated on the stack. If you keep allocating memory on the stack, the stack will eventually overflow.
Veterans, please remember: Once there is a problem with the recursion you write, if the boundary is not found correctly, a
will be reported. If it is reported, This error must be because your termination condition is wrong, or the termination condition is not written, which causes your recursion to be too deep, and eventually the stack overflows.
If we want the above code to be correct, we need to add a termination condition to it.
The correct code is as follows:
public class TestDemo { public static void func(int n){ if(n == 1) return; func(n -1); } public static void main(String[] args) { func(3); } }
The following will give you a deeper understanding of recursion through simple examples
2. The use of recursion
Example: Recursion Method to find the factorial of n Drawing analysis:
Implementation code:
public class TestDemo { public static int fac(int n){ if(n == 1) { return 1; } int tmp = n * fac(n - 1); return tmp; } public static void main(String[] args) { System.out.println(fac(5)); } }
Code drawing explanation:
Example question: Find the sum of n
Drawing analysis:
Implementation code:
第一种写法: public class TestDemo { public static int sumAdd(int n){ if(n == 1) { return 1; } int tmp = n + sumAdd(n - 1); return tmp; } public static void main(String[] args) { System.out.println(sumAdd(3)); } } 第二种写法: public class TestDemo { public static int sumAdd(int n){ if(n == 1) { return 1; } return n + sumAdd(n -1); } public static void main(String[] args) { System.out.println(sumAdd(3)); } }
Example question: Recursive implementation prints each item in order One-digit number
Drawing analysis:
Implementation code:
public class TestDemo { public static void print(int n){ if(n < 10){ System.out.print(n+" "); }else{ print(n/10); System.out.print(n%10+" "); } } public static void main(String[] args) { print(1234); } }
Example: Write a recursive method and input a non-negative integer , returns the sum of the numbers that make up it. For example: if you enter 1729, it should return 1 7 2 9
Implementation code:
public class TestDemo { public static int sumEveryone(int n){ if(n < 10){ return n; }else{ return n%10 + sumEveryone(n/10); } } public static void main(String[] args) { System.out.println(sumEveryone(7910)); } }
Example question: Find the nth Fibonacci number
Drawing analysis:
Implementation code:
第一种方法:递归 public class TestDemo { public static int fib(int n){ if(n == 1 || n == 2){ return 1; }else{ return fib(n-2)+fib(n-1); } } public static void main(String[] args) { System.out.println(fib(5)); } 第二种方法:叫做循环(迭代)实现 public static int fib2(int n){ if(n == 1 || n==2){ return 1; } int f1 = 1; int f2 = 1; int f3 = 0; for (int i = 3; i < n; i++) { f3 = f1+f2; f1 = f2; f2 = f3; } return f3; } public static void main(String[] args) { System.out.println(fib2(45)); }
The above is the detailed content of Java Recursion: Concepts and Usage. For more information, please follow other related articles on the PHP Chinese website!

JVM'sperformanceiscompetitivewithotherruntimes,offeringabalanceofspeed,safety,andproductivity.1)JVMusesJITcompilationfordynamicoptimizations.2)C offersnativeperformancebutlacksJVM'ssafetyfeatures.3)Pythonisslowerbuteasiertouse.4)JavaScript'sJITisles

JavaachievesplatformindependencethroughtheJavaVirtualMachine(JVM),allowingcodetorunonanyplatformwithaJVM.1)Codeiscompiledintobytecode,notmachine-specificcode.2)BytecodeisinterpretedbytheJVM,enablingcross-platformexecution.3)Developersshouldtestacross

TheJVMisanabstractcomputingmachinecrucialforrunningJavaprogramsduetoitsplatform-independentarchitecture.Itincludes:1)ClassLoaderforloadingclasses,2)RuntimeDataAreafordatastorage,3)ExecutionEnginewithInterpreter,JITCompiler,andGarbageCollectorforbytec

JVMhasacloserelationshipwiththeOSasittranslatesJavabytecodeintomachine-specificinstructions,managesmemory,andhandlesgarbagecollection.ThisrelationshipallowsJavatorunonvariousOSenvironments,butitalsopresentschallengeslikedifferentJVMbehaviorsandOS-spe

Java implementation "write once, run everywhere" is compiled into bytecode and run on a Java virtual machine (JVM). 1) Write Java code and compile it into bytecode. 2) Bytecode runs on any platform with JVM installed. 3) Use Java native interface (JNI) to handle platform-specific functions. Despite challenges such as JVM consistency and the use of platform-specific libraries, WORA greatly improves development efficiency and deployment flexibility.

JavaachievesplatformindependencethroughtheJavaVirtualMachine(JVM),allowingcodetorunondifferentoperatingsystemswithoutmodification.TheJVMcompilesJavacodeintoplatform-independentbytecode,whichittheninterpretsandexecutesonthespecificOS,abstractingawayOS

Javaispowerfulduetoitsplatformindependence,object-orientednature,richstandardlibrary,performancecapabilities,andstrongsecurityfeatures.1)PlatformindependenceallowsapplicationstorunonanydevicesupportingJava.2)Object-orientedprogrammingpromotesmodulara

The top Java functions include: 1) object-oriented programming, supporting polymorphism, improving code flexibility and maintainability; 2) exception handling mechanism, improving code robustness through try-catch-finally blocks; 3) garbage collection, simplifying memory management; 4) generics, enhancing type safety; 5) ambda expressions and functional programming to make the code more concise and expressive; 6) rich standard libraries, providing optimized data structures and algorithms.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 Linux new version
SublimeText3 Linux latest version

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Notepad++7.3.1
Easy-to-use and free code editor
