// Simple loop examples in Java

public class SimpleLoops {

    public static void main(String[] args) {

        // while loop, post increment
        int counter = 1;
        while (counter <= 6) {
            System.out.println(counter++);
        }
        System.out.println("===================");

        // while loop, pre increment
        counter = 5;
        while (counter > 0) {
            System.out.println(--counter);
        }
        System.out.println("===================");
        
        // for loop, incrementing
        int i;
        for (i = 2; i < 9; i++)
        {
            System.out.println(i);
        }
        System.out.println("===================");

        // for loop, incrementing
        int j;
        for (j = 7; j >= -1; j--)
        {
            System.out.println(j);
        }
        System.out.println("===================");

        // do while loop
        String string = "Hello There";
        int index = string.length() - 1;
        do {
            System.out.print(string.charAt(index--));
        }
        while (index >= 0);
        System.out.println();
    }
}

© 2012 CS160 Colorado State University. All Rights Reserved.