Loop Control

loop control

Loop control Definition :

A loop control is defined as the block of statement which is repeatedly executed for a certain number of times. There are three types of loops: While , for and do-while.
Why we use Loop ? 
When we need to execute a block of code at several time that time we use looping concept in java .

Advantage of Looping Statement

  •   To reduce the length of code
  •   Less memory space
  •   Time consuming process is reduce, when the programme will execute.
  •   Reducing burden on the developer

Must Know: Complete Java Topics to be a Professional Programmer 

There are three types of Loop Condition :

  • For Loop
  • While Loop
  • do-while loop

For loop :-
The For loop allows to executes a set of instruction untill a certain condition is satisfied. That means, for loop is a statement which allows code  to be repeatedly executed. It contains three part Initialization, Condition and Increment or Decrements.

Syntax :

for ( initialization ; condition ; increment/ decrement )
{
Statement 1 ;
Statement 2 ;
}

flow-of-for-loop

Flow Diagram

loop control

Example of for loop

class  Hello
{
public static void main(String args[])
{
int i;
for (i=0: i<5; i++)
{
System.out.println("Hello Friends !");
}
}
}

Output

Hello Friends !
Hello Friends !
Hello Friends !
Hello Friends !
Hello Friends !

While loop :-
In while loop, the condition may be any expression. the loop statement will be executed till the condition is true .
If the condition is true, the body of the loop is executed, when the condition is false the condition is out of the loop .

Syntax :-
while (condition )
{
Body of the loop
}

Flow DiagramWHILE-Loops-statement

Example while loop

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

Output

1
2
3
4
5

Do- While Loop :-
The body of the loop is always executed atleast once. Since the test condition is eveluated at the bottom of the loop.

Syntax :-
do
{
Statement ;
}
While ( Condition )

Flow Diagram  

dowhile

Example do..while loop

class  dowhileDemo
{
 public static void main(String args[])
 {
 int i=20;
do
 {
System.out.println("Hello world !");
 i++;
}
while(i<10);
}
}

Output

Hello world !

Example do..while loop

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

Output

1
2
3
4
5