Looping and Iteration

Loop with 'while'

while (expression) {
     // statement
}

The while statement executes a block of statements while a particular condition is true

int count = 1;
while (count < 11) {
    System.out.println("Count is: " + count);
    count++;
}

Loop with 'do' - 'while'

do {
     // statement(s)
} while (expression);
int count = 1;
do {
    System.out.println("Count is: " + count);
    count++;
} while (count < 11);

Loop with 'for'

for (initialization; termination; increment) {
    // statement(s)
}
for(int i=1; i<11; i++){
      System.out.println("Count is: " + i);
}

The for statement provides a compact way to iterate over a range of value

Infinite Loop

while (true) {
    // your code goes here
}
for ( ; ; ) {   
    // your code goes here
}

Iterate array with loop

int[] numbers = { 100, 200, 300, 400, 500 };

System.out.println(numbers[0]);
System.out.println(numbers[1]);
System.out.println(numbers[2]);
System.out.println(numbers[3]);
System.out.println(numbers[4]);
int[] numbers = new int[5];

for(int i = 0; i < numbers.length; i++) {
    numbers[i] = i * 100 + 100;
    System.out.println(numbers[i]);
}

Looping in Java

By Nur Ratna Sari

Looping in Java

  • 67