Thursday, April 14, 2005

Iteration

"Q: How do you keep a programmer in the shower all day? A: Give him a bottle of shampoo which says "lather, rinse, repeat.""

Introduction

Iteration is also known as loop or repetition. A statement or a block of statements are executed repeatedly as long as a specified condition is true.

Infinite loop

Program

public class Loop {
    public static void main(String[] args) {
        for(; ; ) {
            System.out.println("Java is cool");
        }
    }
}

Output

Java is cool
Java is cool
Java is cool
Java is cool
Java is cool
...

Infinite counting

Program

public class Loop {
    public static void main(String[] args) {
        for(int i = 0; ; i++) {
            System.out.println(i);
        }
    }
}

Output

0
1
2
3
...

Counting to "ten"

Program

This program counts 10 numbers, from 0 to 9.

public class Loop {
    public static void main(String[] args) {
        for(int i = 0; i < 10; i++) {
            System.out.print(i + " ");
        }
    }
}

Output

0 1 2 3 4 5 6 7 8 9 

Resources