Introduction to Loop in JAVA


Loops in JAVA

There are three types f loop structures in JAVA

What is a Loop?

A Loop is a squance of instructions that are continually repeated until a certain condition is reached or met. We have following three types of loop in JAVA.

  1. while()
  2. do- while()
  3. for loop

Requirements of loop

We require to follow the following steps for writing a loop:

  • for every loop we need a loop control variable with some initializatio value
  • give final test value to this variable inside the loop e.g. while(x<10)
  • Write the body of the loop containing the task to be repeated
  • and inside the loop modify or change the control variable to test for changed value next time the loop executes.

Let us start with the loop

This program explains with simple example the use of while(), do-while() and for(  ;  ;  ) loops. It should be remembered that :

  • while() is a pre-test loo and must be used when the condition si first required to be checked before execution
  • do-while() is a post-test loop and must be used when you want the loop to execute at least once before testing the loop condition
  • for() is also a pre-test loop and test the condition before entering in the loop.

package com.example;
public class loopsJAVA
{
public static void main(String[] args)
{
//initialize the loop contrl variable

int x = 0;
while (x <5) // pre-test loop
{

System.out.println(“!Hello Java”);
x++; // x+= 1; or x=x+1

}
System.out.println(“Now for do while”);
int y=0;
do
{

System.out.println(“! Hello India”);
y++;

} while(y<5); // post test loop, will execute at least once

// for( ; ; ) with blank parameters will run infinite number of times
for(int i=0 ;i<5 ;i++ )
{

System.out.println(“Hello Faridabad”);

}

}

}


Sometimes a loop may enter into an infinite loop for example. When you exactly know how many to run the loop, use the for () loop, when it is not kown in advance as how many times the loop executes, use while()  or do-while() loop

do no add i++ (increment control variable) inside the for() loop as it will increment it twice. there is already the step value inside the for loop (   ;   ;  )

 

error: Content is protected !!