Loops In Java

0
159
Loops-In-Java

 

A situation occurs where we need to execute our set of statements n number of times again and again until the condition satisfies. Loops are mostly commonly used where a single set of code needs to be executed repetitive times.

1.Java Simple For Loop : The For loop is used to initialize variables, check condition and increament/Decrement

Syntax of Simple For Loop:

Example :

OUTPUT :

java for loop example

2.Java for –each loop : For – each loop is mainly used to read complete array or collection in java. We need not increament or decrement the value. The other name for –each loop is dynamic loop, because we are not hard coding the increament or decrement values.

Syntax of for Each Loop:

Example Program on for Each loop : 

OUTPUT :

java for each loop example

Java While Loop : Java while loop is used to iterate the program several times. However the number of iterations are not fixed or known, we can use While loop.

Syntax of While loop :

Example of while loop :

Output :

java while loop example

 

Java do-While Loop  : The java do-while loop is used when the number of iteration is not fixed and we must have to execute the loop at least once. At this time we will use do-while loop.

Syntax of do-While Loop :

 

Program on do-while loop :

Output :

java do while loop example

LEAVE A REPLY

Please enter your comment!
Please enter your name here