Skip to main content
1 of 3
axcdnt
  • 14.7k
  • 7
  • 29
  • 32

Usually recursive methods allow a few lines of code but a deeply thought about your algorithm. If you make a logical mistake, you'll probably obtain a StackOverflowError.

Here follows 2 programming common examples:

Iteractive:

public int calculateIteractiveFactorial(int n) { // Base case if (n == 1) { return 1; } int factorial = 1; for (int i = 1; i <= n; i++) { factorial = factorial * i; } return factorial; } 

Recursive:

public int calculateRecursiveFactorial(int n) { // Base case if (n == 1) { return 1; } return n * calculateRecursiveFactorial(n - 1); } 

Hope you get the idea. It's always good to know how to think about different solutions for any idea, always considering *lines of code, complexity, clarity, etc.

axcdnt
  • 14.7k
  • 7
  • 29
  • 32