A loop (iteration) is a sequence of instructions that is continually repeated until a certain condition is reached. Loops are different in syntax but their basic functionality is same. Loops are beneficial when you’re going to reuse a certain code sequence several times.
There are three main types of loops in java-
for loop
while loop
do-while loop
for loop : A for loop is a repetition control structure that allows you to write a loop that needs to be executed a specific number of times.
A for loop is useful when you know how many times a task is to be repeated.
Syntax-
for ( Initialization; Condition; Increment/ Decrement) {
//code to be executed
}
Initialization- This step executes first and only only once at the beginning of the for loop.
Condition-If it's true the loop execute and the control jump to the Incrementation/ Decrementation
Incrementation/ Decrementation- Here we increment or decrement the loop counter value. this executes at the end of each iteration after the code block has been executed.
Note_ Do not forget to increase the variable used in the condition, otherwise the loop will never end!
Flowchart
Example: The example below will print the numbers 1 to 6
Output:
while loop- When the number of iteration is not fixed we use while loop. it is called entry-controlled loop too. In while loop we only give condition. Initialization we do separately outside the loop. At last we do incrementation/ decrementation in the loop.
Syntax-
Initialization;
while ( Condition) {
//code to be executed
Incrementation/ Decrementation;
}
Flowchart
Example: The example below will print the numbers 1 to 6
Output:
do/while loop- Do/while loop is a variant of while loop. In this loop code executes at least once without fail because it does not check the condition for the first time.
Syntax-
Initialization;
do {
//code to be executed
Incrementation/ Decrementation;
}
while (Condition) ;
Flowchart
Example: The example below will print the numbers 1 to 6
Output: