Loops

While Loop:-

  • A loop statement allows to repeatedly execute a statement or group of statement.
  • A while loop statement repeatedly executes a target statement as long as a given condition is true.
  • A while loop is an entry controlled loop  statement.
Syntax:
Initialization
while (test condition){
     Body of the Loop
}
Example:
int x = 6
while (x < 10){
    System.out.println(x);
    x++;
}
System.out.println("Loop Ended");

For Loop:-

  • Another loop structure is the for loop.A for loop allows you to efficiently write a loop that needs to execute a specific number of times.
  • A for loop is best when the starting and ending number are known.
Syntax:
for(initialization ; condition ; increment/decrement){
     statement(s)
}
Example:
for( int x=1 ; x<=5 ; x++ ){
     System.out.println(x);
}
  • You can have any type of condition & any type of increment statement in the for loop.
Example:
for( int x=0 ; x<=10 ; x+2 ){
    System.out.println(x);
}
Output:
0  2  4  6  8  10

do….while Loop