What Are the 4 types of loops in Java - onlyxcodes

Saturday, 2 July 2022

What Are the 4 types of loops in Java

This article will show you the types of loops in Java with practical examples.


A programming language's basic and crucial idea is the concept of loops.


Imagine that you want to display thousands of entries that have been kept in a database to comprehend what loops are. How would you accomplish that without using loops? Would you firmly program everything to appear on a page? No, this is not the answer.


To perform recurring activities in a few lines of code, "loops" are required.


4 types of loops in Java?

Why do we use loops?

Loop facilitates the tedious repetition of labor.


Think about a scenario where you need to print all numbers between 1 and 1000. Then, what will you do? Will you use a print statement to print every integer between 1 and 1000? That method of operation is illogical.


You may quickly print 1 to 1000 integers with a single line of loop code.


The use of the loop then follows. You can simply do the repetitive, tiresome work by using a loop. The rest is handled by the loop.


It is used to reduce programming workload and speed up execution without taking up extra time.


What is a loop in Java?

Java defines looping as executing various lines of code sequentially unless a condition is untrue.


We don't want the loop to run endlessly, thus the condition is essential. The loop ends as soon as this criterion is met.


There are three basic forms of loops in Java, and the fourth type is an enhanced for loop (for each), which functions similarly to a for loop.


1. for loop


    1.1. Enhanced for loop


2. while loop


3. do-while loop


1. For loop in Java

The Java for loop offers a clear way to express the loop structure. We use a for loop when we know exactly how many times the loop will be executed.


How many parts are there in for loop?


The three main components of a Java for loop define the loop itself.


These are the initialization clause, the test condition, and the increment or decrement clause for the control variable.


The syntax of for loop in Java:


for(initializing statement; condition testing; increment/decrement)
{
   // iterated code 
}

The loop structure begins with the initializing statement. It includes a variable that has a predetermined beginning value set by the coder.


The condition statement in testing specifies the prerequisite for the code block to be executed.


The increment/decrement statement, which comes last, causes a value to change every time a code block in the loop is run.


How does for loop work in Java?


The interpreters constantly maintain the road of which statement is scheduled to be executed when a program runs. This is referred to as the control flow or the program execution flow.


A flowchart can be used to demonstrate the control flow:


for loop flowchart

Step 1: The initialization phase of the for loop only executes once since initialization occurs first in the for loop.


Step 2: Every time a for loop iterates, the condition is checked to see if it is true. If it is, the statements inside the body of the for loop are then performed.


Once the criteria become false, the statements in the for loop are not executed, and control is instead passed to the statement that follows the for loop in the program.


Step 3: The increment/decrement portion of the for loop, which updates the loop counter, runs after each execution of the for loop's body.


Step 4: The control moves directly to step two and reevaluates the condition after the third step.


An example of for loop in Java


class ForLoopExample 
{
  public static void main(String args[]) 
  {
	int a;
	
    for (a = 1; a < 10; a++) 
	{
      
      System.out.println("Value of a = " + a);
    }
  }
}

Output:


Value of a = 1
Value of a = 2
Value of a = 3
Value of a = 4
Value of a = 5
Value of a = 6
Value of a = 7
Value of a = 8
Value of a = 9

Explanation:


Step 1: Before the loop begins, a variable is assigned to 1 (int a = 1).


Step 2: Specifies the prerequisites for the loop to run (a must be less than 10). The loop will repeat itself if the condition is proper and come to an end if it is false.


Step 3: Each time the code block in the loop is executed, a value (a++) is incremented.


1.1. Enhanced for loop in Java

With a few added characteristics, it is similar to a for loop but differs in some ways. When it comes to writing and understanding code, the enhanced for loop helps iterate arrays and collections. You don't even need to be aware of the collection's size.


This enhanced for loop does have some restrictions, though.


Since this loop object is irreversible, the values that are received when the loop is running are interpreted. This loop prevents you from changing the collection's values, although other loops make it simple to do so.


The syntax enhanced for loop in Java:


for(<datatype> <variable_name>:<collection_name>)
{
     // body statement
}

enhanced for loop example:


In the enhanced for loop in the example below, I have declared the str to be a string. 


class EnhancedForLoopExample
{
   public static void main(String args[])
   {
      String arr[]={"USA","Canada","Australia","United Kingdom"};
	  
      for (String str : arr) 
	  {
         System.out.println(str);
      }
	  
   }
   
}

Output:


USA
Canada
Australia
United Kingdom

2. while loop in Java

The while loop's condition is first tested, and if it returns true, the sentences within it are then executed. Whenever the condition returns false, the control leaves the while loop and moves on to the following sentence.


while loop syntax in java:


while (boolean condition)
{
    //loop body 
}

Workflow of while loop:


while loop flowchart

Considering the condition occurs at the beginning of the while loop. If it is determined to be true, the loop's body statements are carried out; otherwise, the first statement after the loop is carried out. It is also known as the Entry control loop because of this.


The statements in the body of the loop are performed once the condition has been assessed as true. In most cases, the statements include an update value for the variable that will be used in the subsequent iteration.


The loop ends, signaling the conclusion of its entire phase when the condition is determined to be false.


Example of while loop in Java:


A loop variable needs to be initialized before the while loop may run. Additionally, the while loop's body should alter the loop variable.


class WhileLoopExample 
{
    public static void main(String args[])
	{
         int a = 5;
		 
         while(a >= 1)
		 {
              System.out.println(a);
              a--;
         }
    }
}

Output:


5
4
3
2
1

3. do-while loop in Java

The while loop and the do-while loop are related. Java do-while loop first runs the statement before checking the condition.


The while loop would not run any statements if the condition were true at the beginning of the loop, whereas in the loop it would still be executed.


Because it checks the condition after the statements inside it are executed, the do-while is an exit-controlled loop.


do while loop syntax in java :


do
{
   // loop body
}
while (condition);

do while loop flowchart

When the statement is executed, the do-while loop begins. That does not do a first-time condition check.


The condition is tested to see if it is true or false after the statements have been executed and the variable value has been modified. The loop iterates again if the condition is determined to be true.


The loop ends, signaling the conclusion of its entire phase when the condition is determined to be false.


Example of do while loop:


class DoWhileLoopExample 
{
  public static void main(String args[]) 
  {
    int a = 0;
	
    do{
		
      a++;
      
      System.out.println("value of a is " + a);

    }while ( a != 5 );
  }

}

Output:


value of a is 1
value of a is 2
value of a is 3
value of a is 4
value of a is 5

Nested loop in Java

A loop is referred to as being nested when it contains another loop within its body.


The inner loop begins after the outer loop's initial iteration.


The outer loop's first iteration ends when the inner loop's iterations are finished, and it then moves on to the second iteration. This continues until the outer loop has completed all of its iterations.


Nesting loops, however, need not always involve two loops. You are allowed to nest as many loops as you like.


Java's Nested Loop Syntax.


1. Nested For loop


for(initialize;cond1;increment/decrement)
{
	for(initialize;cond2;increment/decrement)
	{
		//body of loop2
	}
//body of loop1
}

2. Nested While loop


while(cond1)
{
	while(cond2)
	{
		// body of loop2
	}
//body of loop1
}

3. Nested do-while loop


do{
	do{
		//body of loop 2
	}while(cond2)
//body of loop 1
}while(cond1)

4. Nested heterogenous loop


The ability to nest loops is not restricted to only other loops of a similar type. Any loop can be nested inside another loop; examples include the while loop inside the for loop or the while loop inside the do-while loop, among many more conceivable combinations.


for(initialize;cond1;increment/decrement)
{
	while(cond2)
	{
		//body of loop2
	}
// body of loop1
}

How Nested Loop works in Java?


Each loop contains the following three elements:


Initialization: Initializing the value of the counter is what this step is all about.


Condition: The comparison that must be accurate for the loop to continue to run is referred to by this condition.


Increment/Decrement of counter: This is the action that will be taken once a loop's flow has finished.


The aforementioned three steps are examined for each loop contained in nested loops.


Thus, the inner loop runs entirely for each flow of the outer loop. If there are m flows for the outer loop and n flows for the outer loop, then this loop will run m*n times overall.


A Java program to help you grasp the idea of nested loops:


Here I used nested for loop.


class NestedForLoopExample 
{
  public static void main(String args[]) 
  {
	int a, b;
	
	for (a = 1; a <= 3; a++) 
	{
      for (b = 1; b <= a; b++) 
	  {  
        System.out.print(b);
      }
      System.out.println(" ");
    }
	
  }
  
}

Output:


1
12
123

Infinite loop in Java

If a loop's condition is always true, it will loop infinitely.


We can always make mistakes while designing loops, such as forgetting to update the condition variable or not providing a suitable condition, which causes the loop to run indefinitely.


The methods used by various IDEs to halt the live execution of code differ. Knowing the shortcut in your IDE to halt live program execution is essential in case you have the unfortunate Java infinite loop.


class InfiniteWhileLoop 
{
  public static void main(String args[]) 
  {
    int a = 0;
	
    while(a < 5){
      
      System.out.println("value of a is = " + a);
    }
  }
}


Read Also:

What does double mean in Java

How to Remove a Character from a String in Java

How do you define a method in Java?

What do the replaceAll () do in Java?

Can I use LeetCode for Java?

How to Get the Length of a String in Java

How to make lists of lists in Java?

How to print each word in new line in Java

Why do we use :: (double colon) in Java

What is the Difference Between NoClassDefFoundError and ClassNotFoundException in Java

How to Replace a Character in a String in Java without using the Replace Method

What are Variable Arguments in Java

Context Switching in Java Thread Example

Java Stream Iterate Example

How to Run Package Program in Java using Command Prompt

What is final class and method in Java

What is Encapsulation in Java with Realtime Example

3 Ways to Create Thread in Java

Java Code to Send Email with Attachment

How to Produce and Consume Restful Webservice in Java

No comments:

Post a Comment

Post Bottom Ad