What is Looping Statement ?
- Looping statement is used to execute the block of code repeatedly as long as the specified condition is true.
- Looping is used to reduce the number of lines.
- Instead of writing the same code multiple times , we can use loops to perform that task efficiently.
Types of Looping Statement:
- While Loop
- Do While Loop
- For Loop
While Loop:
- While loop is used to execute the block of code until the specified condition is true.
- While is used when we don't know the number of iterations of loop.
- while loop is an entry-controlled loop , because it checks the condition before executing the block of code.
Syntax:
while(condition) { // block of code } Example:
public class While_Loop { public static void main(String[] args) { int count=1; while(count <= 5) { System.out.println("Iteration no :"+count); count++; } } } Output:
Iteration no :1 Iteration no :2 Iteration no :3 Iteration no :4 Iteration no :5 - The initial value of count is 1 .
- The condition is count <= 5 .
- If the condition is true, it executes the block of code.
- After that it increment the value of count by 1.
- The loop runs until the count becomes 6.
- When the count becomes 6 the condition becomes false and the loop will be ended.
Note:
- If we forget to update the loop variable, the loop may execute infinitely.
Do While Loop :
- Do-while is an exit controlled loop , because it checks the condition after executing the block of code.
- Do-While loop executes at least once , even if the condition is false.
Syntax:
do { //block of code } while(condition): Example:
public class Do_While { public static void main(String[] args) { int count = 6; do { System.out.println("Iteration no:"+count); count++; }while(count <= 5); } } Output:
Iteration no:6 - Initial value of count is 6 .
- The statement inside the loop is executed first.
- Then it increment the count by 1.
- After executing the statement , it checks the condition (count <= 5).
- Here the condition is false , even though the condition is false the loop executed once.
- Because Do while is a Exit controlled loop.
Note:
- If we forget to update the loop variable, the loop may execute infinitely.
For loop :
- For loop is used when we know the number of iteration.
- For loop is an Entry Controlled Loop.
Syntax:
for(initialization; condition ; increment // decrement) { //block of code } Example:
public class For_Loop { public static void main(String[] args) { for(int i=1;i<=5;i++) { System.out.println("Iteration no : "+i); } } } Output:
Iteration no : 1 Iteration no : 2 Iteration no : 3 Iteration no : 4 Iteration no : 5 The for loop contains three parts:
- Initialization (int i=1) – Initializes the variable i with the value 1.
- Condition (i<=5) – Checks whether the condition is true. If true, the loop body executes.
- Increment (i++) – Increments the value of i by 1 after each iteration.


