Understanding Java Looping Statements

In Java, looping statements allow you to execute a block of code repeatedly. The most common looping statements are the for, while, and do-while loops.

for Loop:

The for loop is used to iterate a block of code a specific number of times. It consists of three parts: initialization, condition, and iteration.


for (int i = 0; i < 5; i++) {
  System.out.println("Iteration " + (i + 1));
}

while Loop:

The while loop is used to iterate a block of code as long as a specified condition is true.


int count = 0;

while (count < 3) {
  System.out.println("Count: " + count);
  count++;
}

do-while Loop:

The do-while loop is similar to the while loop but guarantees that the block of code is executed at least once, even if the condition is false initially.


int num = 5;

do {
  System.out.println("Number: " + num);
  num--;
} while (num > 0);

Example:

Here's an example demonstrating the use of looping statements in Java:


// Print numbers from 1 to 5 using a for loop
System.out.println("Using for loop:");
for (int i = 1; i <= 5; i++) {
  System.out.println(i);
}

// Print numbers from 1 to 5 using a while loop
System.out.println("Using while loop:");
int j = 1;
while (j <= 5) {
  System.out.println(j);
  j++;
}

// Print numbers from 1 to 5 using a do-while loop
System.out.println("Using do-while loop:");
int k = 1;
do {
  System.out.println(k);
  k++;
} while (k <= 5);

Note:

Looping statements are essential for performing repetitive tasks in Java. They allow you to execute a block of code multiple times, making your programs more efficient and concise.