Friday, April 22, 2022

From Beginner to Expert: Java Loop Programming

 Loops :

  •   Loops are used to execute a set of statements repeatedly until a particular condition is satisfied.

Types of Loops :

  for loop: This executes a statement a particular number of times.

  while loop: This executes a statement an unknown number of times.

  do-while loop: This executes a statement at least one time.

The syntax for the "for" loop is :

  for(Variable Initialization; Boolean_Expression Test; Increment/Decrement){

   //Statements

}

Example :

package selenium;

public class Java_practise {

public static void main(String[] args) {

  // This will print -- 0,1,2,3,4,5

for(int Increment = 0;Increment<=5;Increment++){

System.out.println("Count is  ==> " + Increment );

}

// This will print -- 5,4,3,2,1,0

for(int Decrement = 5;Decrement>=0;Decrement--){

System.out.println("Count is ==> " + Decrement );

}

// This will print -- 0,2,4

for(int Increment = 0;Increment<=5;Increment+=2){

System.out.println("Skip every one another  ==> " + Increment );

}

// This will print -- 0,1,2,3,4,5

for(int Count = 0;Count<=10;Count++)

{

if(Count==6){

break;

}

System.out.println("Count is ==> " + Count );

}

// This will just print -- 3

            for(int Count = 0;Count<=5;Count++){

             if(Count==3){

         System.out.println("Count is ==> " + Count);

          continue;

}

}

}

}


The syntax for the while loop :
   while(Boolean_Expression Test){
//Statements
}

Example :
package selenium;
public class Java_practise {
   public static void main(String[] args) {
int Count = 0;
// This will print -- 5,10,15,20,25
while(Count < 25){
Count = Count + 5;
System.out.println("Count is ==> "+ Count);
}        
}
}

The syntax for the do-while loop  :
   do{
//Statements
}while(Boolean_Expression Test);

Example :
package selenium;
public class Java_practise {
  public static void main(String[] args) {
int CountOnce = 25;
System.out.println("<==== Next Count ====>");
// This will just print once 
do{
CountOnce = CountOnce + 5;  
System.out.println("Count is ==> "+ CountOnce);
}while(CountOnce < 25);
     
}
}

The syntax for enhanced for loop :
   for (data_type variable: array_name)

Examples :
package selenium;
public class Java_practise {
     public static void main(String[] args) {
// Array of String storing days of the week
    String days[] = { "Mon", "Tue", "Wed", "Thr", "Fri", "Sat", "Sun"};

    // Enhanced for loop, this will automatically iterate on the array list 
    for (String dayName : days) {
      System.out.println("Days ==> "+ dayName);
    }

    System.out.println("<==== Normal For Loop ====>");
    // Normal for loop
    for (int i=0; i < days.length; i++) {
        System.out.println("Days ==> "+ days[i]);

     }
}
}



No comments:

Post a Comment