Loop: Loop are used to execute a statement or a set of statement either a specific number of time or until a particular condition is being executed.
The repetitive operation is done through a loop control instruction.
Types of loops :-
Depending upon the position of a control statement in a program a loop is classified into two types :-
- Entry controlled loop.
- Exit controlled loop.
Entry controlled loop : In this loop a condition is checked in the beginning of the loop body.
While loop & for loop are entry controlled loop.
Exit controlled loop : In this loop , a condition is checked at the end of the loop body.
do-while loop is an exit controlled loop.
Java provide three types of loop:-
- The while loop
- The for loop
- The do-while loop.
While loop: In this loop the condition is given in the beginning of the loop and all the statements are executed till the given condition satisfies.
And when the condition becomes false, the control will move out of the loop.
After exiting the loop , the control may move to the next statement if present.
The body of a loop can contain more than one statement.
In a while loop, if the condition is not true then the body of a loop will not be executed not even once. It is different in the do-while loop.
Syntax:
While (condition)
{
Statement;
}
Example:
// Program to print series of numbers 1 to 10 using while loop.
package com.company;
import java.util.Scanner;
public class learn{
public Staticvoid main(String[]args)
{
int num=1; // initializing the variable
while(num<=10) // while loop wi/n condition
{
System.out.println(num)
num++; //increment operation
}
}
for Loop: This loop has similar functionality as while loop but with different syntax.
For loops are preferred when the number of timer loop statements are to be executed is known before -hand.————-
The loop variable initialization, condition to be tested ,and increment, decrement of the loop variable is done in one line in for loop there providing a shorter , easy to debug structure of looping.
Syntax:
for(initial value;Condition;increment/decrement)
{
Statement;
}
Example:
// Program to print series of numbers 1 to 10 using for loop.
package com.company;
import java.util.Scanner;
public class learn{
public Staticvoid main(String[]args)
{
int i;
for (i=1;i<=10; n++) // for loop to print 1-10 number
{System.out.println(i);
// to print the number
}
}
}
do-while loop: The loop is similar to while loop with the only difference that it checks the condition after executing the statement , i.e. it will execute the loop body one time for sure because it checks the condition after executing the statements.
Syntax:
do{
Statements
}
While(condition)
}
Example:
// Program to print 1 to 10 using do-while loop.
package com.company;
import java.util.Scanner;
public class learn{
public Staticvoid main(String[]args)
{
int i=1; // initializing the unable
do // do-while loop
{
System.out.println(i);
i++; // increment operation.
}
while (i<=10);
}
}