Loops in java
In programming loops are used to repeat a particular group of statements or a single statement for the required number of times.

There are three loops in java.
For loop:-
The syntax of the for loop is given below
for(initialization; condition ; iteration)
{
Java commands
}
Here initialization is to intialize a counter variable.it can be any numeric or character data type depending on the requirement of rhe program.

A counter is required in a loop to count the number of execution taken place.
A counter will be initialized to a value and then we can decide what should be rhe last value of the counter.

The condition is to terminate the loop.
The loop will get executed while the contiion ia true ,when the condition is false the loop will terminate.

Iteration ia used to keep changing the value of the counter because if the value of the counter remains constant the condition remains always true and the loop becomes infinite.

For example
for (int i=1; i<=5;i++)

{
System.out.print(i);

}
This code will print
1 2 3 4 5
Now lets understand what is the order in which the parts of for loop gets executed.

The first is initialisation
(the varaiable.i is asssigt1 , i= 1),after this check the condition,
If the condition is true the statement in the curly brackets are executed, after that the iteration takes place so the value of counter will change , now again rhe condition is checked and the same will be continued untill the condition becomes false, after the condition becomes false rhe loop will get terminated.

While loop:-
It is called an entry controlled loop. The syntax of the while loop is as following.

Initialisation
While(condition)
{
Java statements
}

This is a loop that checks the condition before executing the statements. Initialisation takes place before the loop starts. The loop keeps executing untill the condition becomes false.
While loop can be used in a condition where the number of executions are not fixed.
For example:
int i=1;
while(i<5)
{
i++;
System.out.println(i);
}
The output will be
1 2 3 4 5

Do while loop:-
The next loop is do while loop. It is alao called and exit controlled loop.
The syntax is as follows.

int i=1;
do
{
System.out.println(i);
i++;
}while(i<5);
The output of this loop will be
1 2 3 4 5
The loop is similar to the while loop except the condition is written at the end.
In do…while loop first the java statements are executed without checking the condition , after first execution the condition is checked , now if the condition is true the loop will get executed again, the loop will terminate once the condition becomes false.

LEAVE A REPLY

Please enter your comment!
Please enter your name here