Iteration and Loops

  • For loops let us repeat a command or commands
  • each loop declares a varible that acts as a counter
  • counter variable will be progressed in the loop and can be used for various purposes
public class ForLoop {    
    public static void main(String[] args){
        for (int i = 0; i < 4; i ++){
            System.out.println(i);
        }
    }
}

ForLoop.main(null);
0
1
2
3

while loops do while loops

  • while loops repeat commands while a boolean expression remains true
  • Do While loops check boolean expressions at the end of the loop and at least will run once
public class WhileLoop { 
    public static void main(String[] args){
        int i = 4;
        while (i > 0){
            System.out.println(i);
            i--;
        }
    }
}

WhileLoop.main(null);

Reverse String

public class Reversestring{
    public static void main(String[] args){
        String original = "pupils";
        String reverse = "";

        for(int i = original.length() - 1; i >= 0; i--){
            reverse = reverse + original.substring(i, i + 1);
            System.out.println(reverse);
        }
        
        System.out.println("Final reversed word: " + reverse);
    }
}

Reversestring.main(null);
s
sl
sli
slip
slipu
slipup
Final reversed word: slipup

Nested Loop

  • loop inside a loop
  • outer loop runs once, inner loop will go through entire cycle
  • Nested loops is helpful when it comes to 2D arrays
public class NestedLoop{
    public static void main(String[] args){
        for (int i = 0; i < 2; i++){ //loops 2 times
            for (int j = 0; j< 3; j++){// loops 3 times
                System.out.print("# "); 
            }
        }
    }
}

NestedLoop.main(null);
# # # # # #