Advertisement

Loops in Java with examples

WHAT ARE LOOPS?

In computer programming, a loop is a sequence of instructions that is continually repeated until a certain condition is reached. A loop is a fundamental programming idea that is commonly used in writing programs. Lets suppose we have to print numbers from 1-1000, here we have to print every number with the use of print function and that required much effort and time, for this we can use loop to print these number with the help of one line code (loop).


We have three types of loop in java
1. For Loop
2. While Loop
3. Do While Loop


Do While Loop in Java




FOR LOOP


For loop is usually used to executive a piece of instruction for a specific number of time. The number of iteration depends on the test condition given inside the for loop. it is the most commonly used loop.


SYNTAX OF FOR LOOP


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


JAVA PROGRAM EXAMPLE OF FOR LOOP


Here in this java program example we print those number between 0-100 which are divisible by 2.


class Test
{
public static void main (String[] args)
    {

int number;
for (number =2; number <= 10; number = number + 2)
        {
System.out.println (number);
        }
    }
}


FLOW CHART OF FOR LOOP


flow chart of for loop




WHILE LOOP


while loop is a pre-test loop, it is used when we don't known the number of iteration in advance. It is also called entry control loop. As long as the loop return a value of true, the code inside the loop keep executing. while defining while loop you should keep in mind to set the condition to stop while loop, otherwise, the loop will execute infinitely.


SYNTAX OF WHILE LOOP


while (condition)
{
statement
}


FLOW CHART OF WHILE LOOP


flow chart of while loop



JAVA PROGRAM FOR WHILE LOOP


import.java.util.Scanner;


class While
{
public static void main (String[] args)
    {
int n;
system.out.println("Enter value for condition");
Scanner ref = new Scanner (System.in)
n= ref.nextint();
while (n>= 0)
        {
system.out.println("Learn Coding");
        }
    }
}


DO WHILE LOOP


in do while it is necessary your program must execute at least once no matter if your condition is false. do while is a exit loop, here the body of the statement came before the condition. in while loop we don't use semicolon after condition but here in do while loop we use semicolon after condition.


SYNTAX FOR DO WHILE LOOP


do
{
statement;
}
while (condition);


JAVA PROGRAM FOR DO WHILE LOOP


class Test
{
public static void main (String[] args)
    {
int number = 2;
do
        {
system.out.println(number);
number = number +2
        }
while (number <= 100 );
    }
}



FLOW CHART FOR DO WHILE LOOP


flow chart of do while loop

Click here to learn about method overloading and method overriding in Java



Post a Comment

0 Comments