In programming, we work with data, storing it in variables for easy access and manipulation. We often retrieve information in the application based on the values using if-else statements, operators, and switch statements to control the flow of execution. However, in some use cases, certain actions need to be repeated multiple times, and this is where loops come into play.
In the example below, the same line of code is repeated multiple times, so obviously the output will print "Hi" multiple times which is an inefficient approach.
public class Demo {
public static void main(String a[]) {
System.out.println( "Hi");
System.out.println( "Hi");
System.out.println( "Hi");
System.out.println( "Hi");
System.out.println( "Hi");
}
}
Output:
Hi
Hi
Hi
Hi
Hi
What we want in our code is the ability to write a block of code once, and have it executed multiple times automatically. By utilizing loops, we can avoid redundant code and streamline the process of executing the same set of instructions repeatedly, thereby enhancing the code's readability, maintainability, and performance.
Loop is a feature in java, used to execute a particular part of program repeatedly until a certain condition is met. Java provides three types of loops:
Â
·     for Loop
·     while Loop
·     do-while Loop
Â
For Loop: Â The for loop is used when we know the number of iterations.
Syntax
for (initialization; condition; iteration)
{
//code to be executed
}
Flowchart
Example
public class ForLoop {
public static void main(String[] args) {
for (int i = 0; i < 5; i++) {
System.out.println ("Iteration "Â + i);
}
Output:
Iteration 0
Iteration 1
Iteration 2
Iteration 3
Iteration 4
While Loop:Â The while loop is used when we don't know the number of iterations in advance. The loop continues to execute the code until the specified condition is true.
Â
Syntax
while (condition)
 {Â
// code to be executedÂ
}Â
Flowchart
Example
public class WhileLoop {
public static void main(String[] args) {
       int i = 0;
        while (i < 5) {
            System.out.println("Count " + i);
            i++;
        }
        System.out.println("check " + i);
}
}
       Â
Output:
Count 0
Count 1
Count 2
Count 3
Count 4
check 5Â
Do-while Loop:Â The do-while loop executes the code at least once before the condition is tested, ensuring at least one iteration.
Â
Syntax
Â
do {
 // code to be executedÂ
} while (condition).
Flowchart
 Example
public class Do_while {
public static void main(String[] args) {
        int count = 0;
        do {
            System.out.println("Iteration " + count);
            count++;
        } while (count < 6);
    }
}
Output:
Iteration 0
Iteration 1
Iteration 2
Iteration 3
Iteration 4
Iteration 5
Â
Loops can be nested, which is one loop inside another loop called nested loop.
 This is an example of nested for loop:
Â
public class NestedForLoop {
public static void main(String[] args) {
for (int i = 1; i <= 3; i++) {
System.out.println("Outer loop iteration: "Â + i);
for (int j = 1; j <= 4; j++) {
System.out.println("Inner loop iteration: "Â + j);
}
}
}
}
Output:
Outer loop iteration: 1
Inner loop iteration: 1
Inner loop iteration: 2
Inner loop iteration: 3
Inner loop iteration: 4
Outer loop iteration: 2
Inner loop iteration: 1
Inner loop iteration: 2
Inner loop iteration: 3
Inner loop iteration: 4
Outer loop iteration: 3
Inner loop iteration: 1
Inner loop iteration: 2
Inner loop iteration: 3
Inner loop iteration: 4
 Another example of nested loop (while loop inside for loop) :
 Â
public class NestedLoop {
public static void main(String[] args) {
System.out.println("\nNested Loop:");
for (int a = 1; a <= 3; a++) {
int b = 1;
while (b <= 2) {
System.out.println("outer a= " + a + ", inner b= " + b);
b++;
}
}
}
}
Output:
Nested Loop:
outer a= 1, inner b= 1
outer a= 1, inner b= 2
outer a= 2, inner b= 1
outer a= 2, inner b= 2
outer a= 3, inner b= 1
outer a= 3, inner b= 2
 Below nested loop example prints a multiplication table from 1 to 10.
public class NestedTableLoop {
public static void main(String[] args) {
for (int i = 1; i <= 10; i++) {
for (int j = 1; j <= 10; j++) {
System.out.print(i * j + "\t");
}
System.out.println();
}
}
}
 Output:
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
Now, let’s see the enhanced for loop (also called for-each loop) which iterates over each element in a collection or array.
 In the below example the loop iterates over each element in the numbers array.
public class EnhancedForLoop {
public static void main(String[] args) {
 // Enhanced for loop example
        System.out.println("\nEnhanced For Loop:");
        int[] numbers = {1, 2, 3, 4, 5};
        for (int count : numbers) {
            System.out.println("Number: " + count);
        }
    }
Output:
Enhanced For Loop:
Number: 1
Number: 2
Number: 3
Number: 4
Number: 5
Â
Sometimes, in certain scenarios, a program iterates endlessly, which is called an infinite loop. Generally, this loop is undesirable because it can cause program crashes or system instability. However, in some conditions, infinite loops are intentionally used to check server applications or event-driven programs that run continuously until manually stopped.
Â
Example
public class InfiniteLoop {
public static void main(String[] args) {
//this will just print '1' and will be stuck in an infinite loop***********************
int n=5;
int i= 1;
while (i<n) {
System.out.println( "range"Â + i);
}
}
}
Example to check server application:
The loop continues to execute indefinitely until the user enters "q" to quit the program.
public class ServerApp {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
boolean running = true;
while (running) {
System.out.println("Server is running. Press 'q' to quit.");
String input = scanner.nextLine();
if (input.equals("q")) {
    running = false;
} else {
    System.out.println("Received input: " + input);
}
}
System.out.println("Server has been stopped.");
}
}
By mastering these loops, we can write more efficient, readable, and maintainable Java code. Whether we are performing simple iterations or complex conditional processing, the right loop can significantly streamline our programming tasks.
Â
Thank you for reading!!
Â
Happy Learning :)
Comments