Sitemap

Member-only story

Loops in Java (for, do-while, while)

--

Overview

Looping is a feature that faciliates the execution of set of instruction repeatedly until certain condition holds false. Java provides three types of loop namely the for-loop, while-loop and do-while loop. Loops are also known as iterating statement in Java.

Intrduction to Loops in Java

Imagine that you are asked to print the value of 4 pow(1), 4 pow(2), 4 pow(3),…., 4 pow(9), 4 pow(10).

public class Test {
public static void main(String[] args) {
int x = 4;
/* printing value and multiplying it by 2 every time */
System.out.print(x + " ");
x *= 2;
System.out.print(x + " ");
x *= 2;
System.out.print(x + " ");
x *= 2;
System.out.print(x + " ");
x *= 2;
System.out.print(x + " ");
x *= 2;
System.out.print(x + " ");
x *= 2;
System.out.print(x + " ");
x *= 2;
System.out.print(x + " ");
x *= 2;
System.out.print(x + " ");
x *= 2;
System.out.print(x + " ");

}
}
4 8 16 32 64 128 256 512 1024 2048 

Another way is using loops. Using Looping statements the above code of 10 lines can be reduced to 3 lines.

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

--

--