Simple Explanation of Java Loops

Simple Explanation of Java Loops

If we need to execute a program twice we don’t feel anything wrong with writing the same code twice, but what if we have to run the code more than 10 times or infinite times? It will be a tough call to write that code n number of times and it will make the code messy. In this situation, we need the Java LOOPS statement to execute these programs. In computer programming, a loop is used to repeatedly run a set of instructions or a block of code without having to write it out from scratch each time.

What is Loops?

On the basis of a specific circumstance, the code block is run. A program’s control structures are loops. The coding process is made simpler rather than more efficient when loops are used. When beginners start learning computer programming languages like C, Java, or any other language, they could encounter the question.

Loop control is the common term for this phenomenon. A true condition is one that produces a boolean value of true, while a false condition is one that returns a boolean value of false for all three loop statements.

Also read, Writing Your First Program in Java

Elements in Java Loops

Every loop has specific components or variables that control how it runs. A loop typically includes four components with distinct functions, which are as follows:

Initialization

It is the first condition from where the loop has to start. As it is an optional condition we can use an already existing initialized variable or we can write a new one as per our choice.

Condition

It is the second condition that runs every time in the loop to check the condition. The execution is continued till the condition is false. Either a true or false boolean value must be returned.

Increment/Decrement

As the name represents it is used to increase or decrease the value of the variable and is an optional statement.

Statement

The statement runs till the condition of the loops is false. The loop body is continually run if the value evaluates to true; else, it is terminated.

java loops

Also read, Why Java is so popular among Developers!

Different Types of Loops in Java

for Loops

A block of statements may be executed repeatedly with a set number of times based on the test expression or test condition using Java’s for loop, an entry-controlled loop. The Java loops that are easy to comprehend are those.

While in other Java loop structures, the loop elements are dispersed across the program, all of its loop-control elements are grouped at one location, on top of the loop within the round brackets().

Syntax

for(initialization; condition; updation(increment/decrement))
{
   statement;
}

Example

Print all the numbers from 1 to 5.

public class Main
{
  public static void main (String[]args)
  {
    for (int i = 1; i <= 5; i++){
        System.out.println (i);
    }
  }
}

// Output
1
2
3
4
5

Example

Print the total sum of the first five numbers!

public class Main
{
  public static void main (String[]args)
  {
    int sum = 0;
    for (int i = 1; i <= 5; i++){
        sum = sum + i;
    }
    System.out.println("Sum of first five numbers are:- "+sum);
  }
}

// Sum of first five numbers are:- 15

Also read, Scanning 2.6 Million Domains for Exposed .Env Files

while Loops

The loop-body of a while loop could include a single, multiple, or empty statement. While the test expression or condition is true, the loop continues to repeat. The line immediately following the conclusion of the loop-body code receives program control when the expression is declared false.

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

Syntax

while(condition){
//body
}

Example

Print all the numbers from 1 to 5.

public class Main
{
  public static void main (String[]args)
  {
    int i = 1;
    while (i <= 5){
        System.out.println (i);
        i++;
    }

  }
}

// Output
1
2
3
4
5

Example

Print the 2 multiples from 0 to 5!

public class Main
{
  public static void main (String[]args)
  {
    int j = 0;
    while (j <= 5){
        System.out.println (j * 2);
        //If we doesnt change variable to meet condition, loop will run infinite times
        j++; 
    }
  }
}

// Output
0
2
4
6
8
10

Also read, Understanding Java Math Class And its different methods

do-while Loops

Do-while loops, in contrast to for and while loops, are exit-controlled loops, which means they evaluate their test expressions or test conditions at the bottom of the loop after executing the loop’s body of statements.

Because of this, the do-while loop always runs at least once.

Do-while loops, as opposed to for-and-while loops, are exit-controlled loops, which means they execute the body of the loop before evaluating the test expressions or test conditions at the bottom of the loop.

The do-while loop consequently always executes at least once. The do-while loop is frequently employed in menu selection systems where the user can view the menu at least once. Following that, it is either repeated or ended based on the user’s answer. ‌ ‌

Syntax

do{
    statement(s);
 } while(test-expression);

Example

Print all the characters from A to E.

public class Main
{
  public static void main (String[]args)
  {
    char ch = 'A';
   do{
     System.out.println( ch + " " );
     ch++;
   } while(ch <= 'E');

  }
}

// Output
A
B
C
D
E

Example

Even though in the below code, the condition is not met, the body gets executed for once!

public class Main
{
  public static void main (String[]args)
  {
    char ch = 'A';
   do{
     System.out.println( ch + " " );
     ch++;
   } while(ch < 'A');

  }
}

// Output
A

Also read, Understanding Java Conditional Statement with Flowcharts

Java ‘break’ and ‘continue’ to a statement

The jump statements, break and continue, are used to bypass certain statements inside the loop or end the loop right away without running the test expression. Any loop, including the for, while, and do-while loops, can employ these statements inside of it.

Break: To end a loop quickly in Java, use the break command. A loop’s iteration ends when a break statement is met, and control is instantly transferred to the first statement after the break. Break statements are generally used when we are unsure of the precise number of loop iterations or when we wish to end the loop based on a condition.

By bypassing the conditional expression and any remaining code in the loop’s body, the break forces the instant termination of a loop. Only the innermost loop will be broken out of when we use break inside nested loops.

Example

In the below code, here even though the loop condition is not met, the loop end due to a break statement.

public class Main
{
  public static void main (String[]args)
  {
    for (int i = 0; i < 10; i++) {
       if (i == 5)
            break;
            System.out.println("i: " + i);
        }
        System.out.println("Out of Loop");
  }
}

// Output
i: 0
i: 1
i: 2
i: 3
i: 4
Out of Loop

Example

In the below code, with the help of the continue statement, we don’t print any even number.

public class Main
{
  public static void main (String[]args)
  {
    for (int i = 0; i < 10; i++) {
       if (i % 2 == 0){
            continue;
        }else{
            System.out.println("i: " + i);
        }
    }
    System.out.println("Out of Loop");
  }
}

// Output
i: 1
i: 3
i: 5
i: 7
i: 9
Out of Loop

Also read, Things you don’t know about the Java Switch statement

Final Words

As we have read Incremental tasks would be challenging to complete without loops, which are a fundamental idea in programming. Java programmers would be able to easily create programs that could manage repetitive tasks if they had a solid understanding of loops. we need the LOOPS program to execute these types of programs.

In computer programming, a loop is used to repeatedly run a set of instructions or a block of code without having to write it out from scratch each time. Loop control is the common term for this phenomenon. A true condition is one that produces a boolean value of true, while a false condition is one that returns a boolean value of false for all three loop statements.


Comments

Leave a Reply

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