Introduction to Recursion
Recursion is a powerful technique in programming that involves a function calling itself. It is based on the principle of 'divide and conquer,' where a problem is broken down into smaller, more manageable subproblems.
In recursive algorithms, a problem is solved by solving smaller instances of the same problem, until a base case is reached where the problem can be directly solved without further recursion.
By using recursion, we can express complex problems in an elegant and concise manner by leveraging the repetitive nature of the problem.
Recursion is especially useful for problems that can be naturally defined in terms of smaller instances of the same problem. It allows us to tackle problems that may be difficult or cumbersome to solve using iterative approaches.
To illustrate the concept of recursion, let's consider the classic example of the Fibonacci sequence. The Fibonacci sequence is a series of numbers where each number is the sum of the two preceding ones: 0, 1, 1, 2, 3, 5, 8, 13, 21, and so on.
Here's a Java code snippet that calculates the Fibonacci sequence using recursion:
1public class Fibonacci {
2 public int calculateFibonacci(int n) {
3 if (n <= 1) {
4 return n;
5 }
6
7 return calculateFibonacci(n - 1) + calculateFibonacci(n - 2);
8 }
9
10 public static void main(String[] args) {
11 Fibonacci fibonacci = new Fibonacci();
12 int n = 10;
13 for (int i = 0; i <= n; i++) {
14 System.out.println(fibonacci.calculateFibonacci(i));
15 }
16 }
17}
xxxxxxxxxx
class Main {
public static void main(String[] args) {
// replace with your Java logic here
for(int i = 1; i <= 100; i++) {
if(i % 3 == 0 && i % 5 == 0) {
System.out.println("FizzBuzz");
} else if(i % 3 == 0) {
System.out.println("Fizz");
} else if(i % 5 == 0) {
System.out.println("Buzz");
} else {
System.out.println(i);
}
}
}
}