Looping is a feature in a programming language that provides you the facility to run a set of instructions/functions repeatedly under some conditions.
In java, there are three ways to execute the loops. All the ways are similar in terms of basic functionalities but they are different in terms of syntax and checking time.
1. while loop:
Syntax:
Flowchart:
While loop starts by checking the given condition first. If the given condition is true, then the statements in the loop executed else the first statement following the loop will be executed. That's why it calls an Entry control Loop.
When the condition is checked and true, all the statements inside the loop body are executed.
When the condition becomes false, then the loop will be terminated and end the cycle.
Example
// Java Program to illustrate while looppublic class while1 {public static void main (String args[]){// Defining variableint n=1;// Exit when n becomes greater than 10while (n<=10){System.out.println( "Value of n: "+n);//Increment the value of n for next iterationn++;}}}
Output
Value of n: 1
Value of n: 2
Value of n: 3
Value of n: 4
Value of n: 5
Value of n: 6
Value of n: 7
Value of n: 8
Value of n: 9
Value of n: 10
2. for loop:
In Java for loop is a control flow statement which iterates the part of the programs multiple times. A for statement contains the initialization, condition, and increment/decrement which is shorter and easy to debug.
Syntax:
for (initialization condition; testing condition;increment/decrement){statement(s)}
Flowchart:
Example
class forLoopDemo{public static void main(String args[]){// for loop begins when x=2// and runs till x <=4for (int x = 1; x <= 5; x++)System.out.println("Value of x:" + x);}}
Output
Value of x:1
Value of x:2
Value of x:3
Value of x:4
Value of x:5
Enhanced For loop
In java 5, Java introduced another version of for loop. Enhanced for loop gives a simple way to iterate through the elements of collection or array. It should be used only when there is a need for iteration through the elements in a sequential manner without knowing the index.
Syntax
public for (T element:Collection obj/array){statement(s)}
Example
// Java program to illustrate enhanced for looppublic class enhancedloop{public static void main(String args[]){String array[] = {"Sam", "Henry", "Dom"};//enhanced for loopfor (String x:array){System.out.println(x);}/* for loop for same functionfor (int i = 0; i < array.length; i++){System.out.println(array[i]);}*/}}
Output
Sam
Henry
Dom
3. do-while:
The only difference between the while loop and the do-while loop, do-while loop check the condition after executing the statements. It is also an example of the Exiting control loop.
Syntax
Flowchart
Example
// Java program to illustrate do-while loopclass dowhileloop{public static void main(String args[]){int x = 21;do{// The line will be printed even// if the condition is falseSystem.out.println("Value of x:" + x);x++;}while (x < 15);}}
Output
Value of x: 21
0 Comments