Iterative constructs in Java are used to execute a block of code repeatedly until a specified condition is met. Java provides several types of iterative constructs, primarily using loops (`for`, `while`, `do-while`) and recursion. Here’s an overview of each:
### 1. `for` Loop:
The `for` loop is used when the number of iterations is known before the loop starts. It consists of three parts: initialization, condition, and increment/decrement.
**Syntax:**
for (initialization; condition; update) {
// Code to be executed repeatedly
}
```
**Example:**
```java
for (int i = 1; i <= 5; i++) {
System.out.println("Iteration: " + i);
}
```
### 2. `while` Loop:
The `while` loop executes a block of code as long as a specified condition is true. It is used when the number of iterations is not known beforehand and depends on a condition.
**Syntax:**
```java
while (condition) {
// Code to be executed repeatedly
}
```
**Example:**
```java
int i = 1;
while (i <= 5) {
System.out.println("Iteration: " + i);
i++;
}
```
### 3. `do-while` Loop:
The `do-while` loop is similar to the `while` loop, but it guarantees at least one execution of the block of code before checking the condition. It is used when you want the loop to execute at least once regardless of the condition.
**Syntax:**
```java
do {
// Code to be executed repeatedly
} while (condition);
```
**Example:**
```java
int i = 1;
do {
System.out.println("Iteration: " + i);
i++;
} while (i <= 5);
```
### 4. Nested Loops:
Java allows you to nest loops within each other to execute complex iterative tasks. Nested loops can be `for`, `while`, or `do-while` loops inside another loop.
**Example of Nested `for` Loop:**
```java
for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= 3; j++) {
System.out.println("i: " + i + ", j: " + j);
}
}
```
### Recursion:
Recursion is another technique for iteration where a method calls itself to solve a problem by breaking it down into smaller subproblems.
**Example of Recursion:**
```java
public class Factorial {
public static void main(String[] args) {
int number = 5;
long factorial = computeFactorial(number);
System.out.println("Factorial of " + number + " = " + factorial);
}
public static long computeFactorial(int n) {
if (n == 0 || n == 1) {
return 1;
} else {
return n * computeFactorial(n - 1);
}
}
}
```
### Control Flow Statements:
- **`break` Statement**: Terminates the loop and transfers control to the next statement.
- **`continue` Statement**: Skips the current iteration and continues with the next iteration of the loop.
Iterative constructs are fundamental for repetitive tasks in programming, allowing you to efficiently process data, iterate through collections, and solve problems that require repeated execution of code blocks. Choosing the right type of loop depends on the specific requirements and structure of your program.