In programming, sometimes there is need to execute the block of code repeatedly while some condition evaluates to true. The execution of the set of instructions depends upon a particular condition.
In Java, there are three types of loops.
- for loop
- for each loop
- while loop
- do-while loop
for loop:
In Java, for loop is similar to C and C++. It enables us to initialize the loop variable, check the condition, and increment/decrement in a single line of code.
For loop is used only when we exactly know the number of times, we want to execute the block of code.
syntax:
for(initialization, condition, increment/decrement) {
//block of statements
}
for-each loop:
Java provides an enhanced for loop to traverse the data structures like array or collection. In the for-each loop, there is no need to update the loop variable.
The syntax to use the for-each loop in java is given below:
for(data_type var : array_name/collection_name){
//statements
}
while loop:
The while loop is also used to iterate over the number of statements multiple times.
Unlike for loop, the initialization andincrement/decrement doesn't take place inside the loop statement in while loop. It is also known as the entry-controlled loop since the condition is checked at the start of the loop. If the condition is true, then the loop body will be executed; otherwise, the statements after the loop will be executed.
while(condition){
//looping statements
}
0 comments:
Post a Comment