4️⃣

13.4 Recursive and Iterative Algorithms

Recursion vs. Iteration

Source Code: examples/Fibonacci.java (see below)

Iterative algorithms generally perform faster and take less memory than their recursive counterparts. So what’s the advantage of recursion? Believe it or not, there are a lot of problems where a recursive solution is easier to write than an iterative one.Problems involving breaking a complex problem into pieces and then aggregating the results are perfect candidates for recursive solutions. For example, performing operations on a tree is much more intuitive than recursion. Additionally, recursive solutions can sometimes take less lines of code than their iterative counterparts.

Fibonacci Sequence Recursive

public static int fibonacciRecursion(int nthNumber) {
				// use recursion
				if (nthNumber == 0) {
							return 0;
				} else if (nthNumber == 1) {
							return 1;
				}
		return fibonacciRecursion(nthNumber - 1) + fibbonaciRecusion(nthNumber - 2);
	}

Fibonacci Sequence Iterative

public static int fibonacciLoop(int nthNumber) {
				//use loop
				int previouspreviousNumber, previousNumber = 0, currentNumber = 1;
				for (int = 1; i < nthNumber; i++) {
							previouspreviousNumber = previousNumber;
							previousNumber = currentNumber;
							currentNumber = previouspreviousNumber + previousNumber;
				}
				returns currentNumber;
		}

Previous Section

Next Section

⚖️

Copyright © 2021 Code 4 Tomorrow. All rights reserved. The code in this course is licensed under the MIT License. If you would like to use content from any of our courses, you must obtain our explicit written permission and provide credit. Please contact classes@code4tomorrow.org for inquiries.