Table of Contents

for

   for ( init; condition; increment ){
    statements;    
    }

description of for

a for loop do statements while the condition is true/untrue, the increment counts the loop, it is possible to use more than 1 condition in the for loop

example 1 of for in java

 
package codereferececomjava;
 
public class CodeRefereceComJava {
 
 
    public static void main(String[] args) {
 
        int myOtherCount=5;
 
 
        for (int i = 0; i <= myOtherCount; i++) {
            System.out.println("i is: "+ i + " <= " + myOtherCount );
         }
 
    }
}

output of for example 1 in java

  i is: 0 <= 5
  i is: 1 <= 5
  i is: 2 <= 5
  i is: 3 <= 5
  i is: 4 <= 5
  i is: 5 <= 5

example 2 of for in java

with 2 conditions

package codereferececomjava;
 
import java.util.Scanner;
 
public class CodeRefereceComJava {
 
 
    public static void main(String[] args) {
 
        Scanner keyboard = new Scanner(System.in);
        int passwd=12345;
        int typedIn = 0;
 
        // 2 conditions in for loop
        for (int i = 0; i < 3 && passwd != typedIn; i++) {
            System.out.print("please enter 12345 between 3 attempts: " );
            typedIn = keyboard.nextInt();
         }
 
        if (passwd == typedIn) {
            System.out.println("Success");
        } else {
            System.out.println("Failure");
        }
 
    }
}

output of for example 2 in java

  please enter 12345 between 3 attempts: 42
  please enter 12345 between 3 attempts: 12345
  Success