Introduction to Loops
Learn the loops for a fixed number of iterations in Java.
Repetition
The repetition of an instruction or a group of instructions is a commonly encountered phenomenon in programming. It is called a loop. As an example, say we want our program to perform the following tasks:
- To read a document or data file line by line repeatedly until the end of the file.
- To draw an image pixel by pixel repeatedly using color values that show it on the screen.
- To iterate through a collection of variables one by one to process its values.
- To compute a result by applying a formula to several values.
Let’s say we want to display integers from to . We can simply display the numbers to one by one using the System.out.println()
statement. We can also use one variable and print its value repeatedly by changing the value of the variable, as shown below:
//Multiple print statements with help of variable aclass Test{public static void main(String[] args){int a = 0;System.out.println(a);a = 1;System.out.println(a);a = 2;System.out.println(a);a = 3;System.out.println(a);a = 4;System.out.println(a);}}
The code above clearly shows the repetitive use of System.out.print(a)
. The benefit of using a single variable is that we can convert this repetition into a loop in Java.
The counter-controlled loop
The counter-controlled loop is used when a group of instructions needs to be repeated a fixed number of times. This loop has four parts after the for
keyword as shown below:
for (initialization; condition; update){// body of loop}
The initialization value initializes the counter and is executed only once. The condition value checks the value of the counter at the start of each iteration before ...