Wednesday, October 27, 2021

Loop Statements

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. 

  1. for loop
  2. for each loop
  3. while loop
  4. 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.

syntax:

while(condition){    

//looping statements    

}  

do-while loop:

The do-while loop checks the condition at the end of the loop after executing the loop statements. It is also known as the exit-controlled loop since the condition is not checked in advance.

syntax:

do     

{    

//statements    

while (condition);  


0 comments:

Post a Comment

Data Structures with C++



NET/SET/CS PG



Operating Systems



Computer Networks



JAVA



Design and Analysis of Algorithms



Programming in C++

Top