Looping statements in Java allow you to repeatedly execute a block of code as long as a certain condition is true. Additionally, Java also has an enhanced for loop for iterating through arrays or collections.
Here’s how the while statement works
Syntax :-
while (condition)
{
// Statements Write Hare.
}
Example :-
int count = 1;
while (count <= 5)
{
System.out.println(“Count is : ” + count);
count++;
}
Output :- Count is : 1
Count is : 2
Count is : 3
Count is : 4
Count is : 5
While loops can be used to implement a wide variety of tasks, such as printing a list of items, calculating a sum, or searching for a specific value.
2. Do-While :- In Java provides a “do-while” statement, which is a variation of the “while” loop. The “do-while” loop is used to execute a block of code at least once and then repeatedly execute it based on a specified condition.
Syntex :-
do {
// Write Statements hare.
} while (condition);
Here’s how the “do-while” loop works
Example :-
int i = 1;
do{
System.out.println(i);
i++;
}while (i <= 5);
Output :- 1
2
3
4
5
In this example:-
3. For loop :- A “For” Loop is used to repeat a specific block of code several times. We can initialize the variable, check condition and increment/decrement value. It consists of four parts
Syntex :- for( Init; Condition; Increment )
{
// Statements Write hare.
}
Example :-
// create an array of numbers
int[] numbers = {1, 2, 3, 4, 5};
// print the elements of the array using a for loop
for (int num : numbers)
{
System.out.println(number);
}
Output :- 1
2
3
4
5
This example uses a for-each loop, which is a simplified version of the for loop that is used to iterate over arrays and collections.
For loops can be used to perform a variety of tasks, such as:
4.Nested For loop :- A nested for loop is a loop inside another loop. Nested for loops can be used to solve a variety of problems. For example, we can use nested for loops to print a 2D matrix, iterate over a multi-dimensional array, or generate complex patterns.
Syntex :- // Outer loop
for( Init; Condition; Increment )
{
// Inner loop
for( Init; Condition; Increment )
{
// Statements Write hare.
}
}
Example :-
Int n=1;
// Outer loop iterates from 1 to 3
for (int i = 1; i <= 3; i++)
{
// Inner loop iterates from 1 to i
for (int j = 1; j <= 3; j++)
{
System.out.print(n);
}
System.out.println(); / / This Statement has been written to go on a new line.
}
Output :- 1 2 3
4 5 6
7 8 9
In this example, the outer loop iterates from 1 to 3. For each iteration of the outer loop, the inner loop iterates from 1 to 3. This means that the code inside the inner loop will be executed 3 times for each iteration of the outer loop.