🎓 Get Full Quality Study Materials & Lab ManualsFollow our blog using the button below!  |  📺 Subscribe our YouTube Channel "Lectures by Ravula Govardhan" for Programming Contents!  | 
NEW Experiment #3 — Book Rating & Review System (Node.js + Express) is now live. Read it here →

Java Loops Explained: While, For, and Do-While Loops

Introduction to loops:

There are 3 loops

1. While loop

2. For loop

3. Do while loop

1. While loop:

It checks the condition first whenever condition becomes true it enters into the loop and the loop will be repeated until the condition will be false. If the condition is false, the controller comes out of the loop.

Syntax: 

while(condition) {

...

...

}


Example: 

for example i=1;

while(i<=10) {

System.out.println(i);

i++; //value is post incremented every time.

}

Here output is 1...10 is printed.

2. For loop: 

It initializes the value first, after that it checks the condition whenever it is true it enters after that it increment the value again like that it processed.

Syntax:

for(initialization; condition; incrementation) {

...

...

}


Example:

for(int i=1;i<=10;i++) {

System.out.println(i);

}

3. doWhile:

It enters into the loop without checking the condition first after executing the statement one time then it checks the condition if it is true the loop will be repeated otherwise the controller comes out of the loop.

Example:

int i=1;


do {

System.out.println(i);

i++;

} while(i<=10);

Figure: While vs for vs Do-While: Loop Execution Flow

<Introduction to class and object - Previous                          Next - Introduction to DataTypes>

0 Ravula Kartheek:

Post a Comment