Loops in Java

Loops in Java

Examples of Java Loops

Loops in Java

A loop in Java is a programming construct that allows you to execute a block of code repeatedly, either for a specific number of times or until a certain condition is met. Loops are used to automate repetitive tasks and to iterate through collections of data.

Java provides three main types of loops:

  1. Java for loop
  2. For-each loop
  3. Java while loop
  4. Java do…while loop

Loops can have inside loop(s) which are called Nested Loops.

1. Java for Loop

The for loop is used when you want to perform the number of iterations on a block of code  for a certain number of times. It consists of an initialization, a condition ( termination expression), and an iteration block of code.

  1. Initialization : To initialize a variable as a first value for condition check. It executes only once when loop begins.

  2. Condition ( termination expression): Utmost you want to iterate loop. Condition is validated before each iteration. If the condition becomes false, the loop terminates.

  3. increment/decrement : Increase/decrease initialized variable value in each iteration,so that condition could be false at some point. Otherwise it will be stuck in an infinite loop.

  4. For loop block : Block of code within parentheses of for loop. Code written in this block executes each time when condition is true.
For loop block
Standard Syntax:

for (initialization; condition; increment/decrement) {
    // for loop block of code to be executed in each iteration
}

Like in below for loop example :

  1. variable ‘i’ is initialized as int
  2. Condition is applied as ‘i’ is less than or equal to 5 ( i<=5) 
  3. Incrementing ‘i’ to
for (int i = 1; i <= 5; i++) {

    System.out.println("Iteration " + i);

}

Infinite ‘for’  loop 

In ‘for’ loop expressions are optional. Means while using ‘for’ loop, any or all the expressions can be skipped but it may result in an infinite loop. 

Like in below programs

Program#1: Not given any expression. This kind of ‘for’ loop falls in infinite loop as looping is not terminating in any way.


for (; ;) {
	System.out.println("Iterate!!");
}

Program#2: variable initialization is given but termination and increment/decrement condition to break loop not given. This kind of ‘for’ loop also results in an infinite loop.

for (int i=0 ; ;) {
	System.out.println("Iterate!!");	
}

Program#3: Termination condition is given, but the value of ‘i’ remains the same in each iteration. It is not increasing to terminate the loop. So this kind of ‘for’ loop also results in an infinite loop.
int i = 0;
for (; i < 10;) {
   System.out.println("Iterate!!");
}

Program#4: Although the value of ‘i’ increases in each iteration but termination condition is not given. So this kind of ‘for’ loop results in an infinite loop.


int i = 0;
for (;;i++) {
   System.out.println("Iterate!!");

}

Above mentioned syntax and ways are defined as per standard syntax. In java programming you can use multiple ways to do things. In ‘for’ loop, to break the loop, you can use break statement as  per your requirement. You can even define the condition inside for block and write code to break. But that will not be the correct way to utilize the feature and ease of for loop.

2. for-each loop or Enhanced for loop

This is one another form of ‘for’ loop  that is designed to iterate through arrays and collection objects. This is called an ‘Enhanced for loop’. It makes the loop more compact and easy to apply. Since it starts from the starting element to the last element of the collection that is why an infinite loop may not be possible.

for-each loop cannot traverse the elements in reverse order. You also do not have the option to skip any of the elements because it does not work on an index basis. Moreover, you cannot also traverse the odd or even elements.

Syntax of for-each loop:
 
for(data_type variable : array | collection){  
//body of for-each loop  
}  
Java for-each loop consists of 
data_type with the variable name
 colon (:) : 
array or collection 

Java for-each loop on Array example  : 

int[] numbersArray = { 11, 22, 33, 44, 55, 66, 77, 88, 99, 100 };
for (int number : numbersArray) {
      System.out.println("Number is: " + number);
}

Java for-each loop on collection example  : 

ArrayList<String> employees = new ArrayList<String>();
		employees.add("Ram");
		employees.add("Mohan");
		employees.add("Siya");
		employees.add("Rukmani");
		employees.add("Diya");
		
		for (String empName : employees) {
			System.out.println("Employee Name :" + empName);
		}

3. while Loop

The ‘while’ loop is used when you want to execute a block of code repeatedly as long as a given condition is true. In the ‘while’ loop, condition is checked before each executing block of while. boolean condition is applied in ‘while’ loop

Syntax of while loop

while (condition) {
    // code to be executed in each iteration
	//Change in condition variable to iterate or terminate the loop
}
Examples of while loop:

int count = 0;
while (count < 3) {
    System.out.println("Count: " + count);
    count++;
}


Another Example:
 
int count = 10;
while (count > 3) {
    System.out.println("Count: " + count);
    --count;
}


Infinite while loop : while loop will fall in infinite loop when iteration conditions will not be false. 


Like: 

 In this example: variable count is always 10. Since count value is not decreasing to make the iteration condition false hence condition is always true and loop is iterating infinitely.
int count = 10;
while (count > 3) {
    System.out.println("Count: " + count);

}

In this example below : While condition is always boolean ‘true’ hence loop will be iterating infinitely.


while (true) {
    System.out.println("Iterating while loop: ");

}

4. do-while Loop

The do-while loop is similar to the while loop, but it guarantees that the code block is executed at least once, even if the condition is false. The termination condition is checked after each iteration.

Syntax of do-while loop:

do {
    // code to be executed in each iteration
} while (Termination condition);


Example of do-while loop

int num = 5;
do {
    System.out.println("Number: " + num);
    num--;
} while (num > 0);

Nested Loops

Nested loops are used when you have one loop inside another loop. This is often used for tasks that require iteration over multiple dimensions, such as working with a 2D array or generating patterns.

Nested for loop example:  To generate mathematics tables from 1 to 12 like below we will be needing the help of nested loops.

1	2	3	4	5	6	7	8	9	10	
2	4	6	8	10	12	14	16	18	20	
3	6	9	12	15	18	21	24	27	30	
4	8	12	16	20	24	28	32	36	40	
5	10	15	20	25	30	35	40	45	50	
6	12	18	24	30	36	42	48	54	60	
7	14	21	28	35	42	49	56	63	70	
8	16	24	32	40	48	56	64	72	80	
9	18	27	36	45	54	63	72	81	90	
10	20	30	40	50	60	70	80	90	100	
11	22	33	44	55	66	77	88	99	110	
12	24	36	48	60	72	84	96	108	120	

Here, Inner loop is running 10 times(from 1 to10) to generate table,  while  outer loop is iterating from 1 to given size =12 (upto which number we want to generate the tables)

int size = 12;
		 for (int i = 1; i <= size; i++) {
	            for (int j = 1; j <= 10; j++) {
	                System.out.print(i * j + "\t");
	            }
	            System.out.println(); // Move to the next line after each row
	        }

Nested while loop example: In this example nested for loop is used to generate asterisks (*) piramid like this

* 
*  * 
*  *  * 
*  *  *  * 
*  *  *  *  *

To generate it we need an outer while loop that controls the number of rows (numRows) and inner while loop that controls the number of asterisks (*) to be printed in each row

int numRows = 5;
	        int row = 1;


	        while (row <= numRows) {
	            int col = 1;
	            while (col <= row) {
	                System.out.print("* ");
	                col++;
	            }
	            System.out.println();
	            row++;
	        }

Conclusion

Java loop constructs can be used to perform various tasks, such as iterating through arrays, processing collections, implementing algorithms, and more. When using loops, it’s important to consider loop termination conditions to avoid infinite loops, and to ensure the loop executes the desired number of times or until a specific condition is met.

P.S. We welcome your feedback. Please comment, if you find anything incorrect, or want to share more information about the topic or want to share any kind of feedback.

Leave a Reply

Your email address will not be published. Required fields are marked *