for java videos click
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.
The syntax of the for loop is given below
for(initialization; condition ; iteration)
Here initialization is to initialize a counter variable.it can be any numeric or character data type depending on the requirement of the 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 (int i=1; i<=5;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.
It is called an entry controlled loop. The syntax of the while loop is as following.
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.
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.
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.