Loops
are used to iterate sets of instructions through code blocks for a set number of times.
Three types of loops:
- while loop
- for loop
- do while loop
While Loop
will continue to execute instructions as long as the conditions are True
class Main {
public static void main(String args[]) {
int x = 5, y = 10;
while( x < y ) {
System.out.print("value of x : " + x );
x++;
System.out.print("\n");
}
}
}
Output
value of x : 5
value of x : 6
value of x : 7
value of x : 8
value of x : 9
For Loop
are similar to while loops, but are much more convenient to write.
class Main {
public static void main(String args[]) {
for (int x = 5,y = 10; x <= y; x++)
System.out.println("Value of x:" + x);
}
}
Output :
Value of x:5
Value of x:6
Value of x:7
Value of x:8
Value of x:9
Value of x:10
do while Loop
gives a set of instructions to carry out while certain conditions are being met
class Main {
public static void main(String args[])
{
int x = 5;
do
{
//Instruction
System.out.println("Value of x:" + x);
x++;
}
// Condition being met
while (x < 10);
}
}
Output :
Value of x:5
Value of x:6
Value of x:7
Value of x:8
Value of x:9
Value of x:10