Search

Wednesday, April 7, 2021

Loops in Java

 



Loop Definition


In computer programming, loops are used when you want to repeat some specific block of code. That repetition depends upon the condition, I.e. the specific block of code will be executed until some specific condition fulfill.

Different programming languages support loops and every language has its own syntax for them. There are different types of loops. Most popular are


  • While Loop
  • Do-while Loop
  • For Loop

 

While Loop


While loop is a type of loop which will execute block of code as long as the condition is valid. When the condition is true, the block of code will be executed again and again. When condition answer is false, the while loop will stop and will terminate its execution.


Syntax

While (condition here)

{
//code
}


Example

Printing numbers from 1 to 10 using While Loop

class whileLoopTest

{

          public static void main (String[] ar)

{
int number;
number=1;

while(number<=10)
{
System.out.println(number);

number++;
}

}

}

Output:

12345678910


Do-while Loop


The do-while loop in Java is similar to while loop with one major difference i.e. the code inside the body of loop will be executed one time before checking the condition. If the condition is true, the code in the body of loop will be executed and If the condition is false in start, still you will get the output one time.


Syntax

do
{
//code here
}
while (condition to check)

 

Example 1

class DoWhileTest

{

          public static void main (String[] ar)

          {

int number;

number = 1;

do

                    {

                    System.out.println (number);

                    number++;

                    } while (number<=10);

}

}

Output

12345678910


Example 2

class DoWhileTest

          {

          public static void main (String[] ar)

{

int number;

number = 1;

do

                    {

                    System.out.println (number);

                    number++;

                    } while (number>10);

}

}

Output

1

 

For Loop


In Java, if you want to repeat a block of code to a specific number of time, then we can use for loop. In for loop, we have starting point and ending point. If programmer already knows about the number of iteration, then for loop is good to use


Syntax


for (variable initialization; condition to check; increment or decrement)
{

//code

}

 

For Example

class ForLoopTest

          {

          public static void main (String[] ar)

          {

                    for (int number=1;number<=10;number++)

                    {

                    System.out.println(number);

                    }

          }

}

Output

12345678910


No comments:

Post a Comment