This is used to execute the program repeatedly until a specific condition is met.
Three types of loops are;
- for loop.
- while loop.
- do-while loop.
for loop;-
Syntax:-
For(initialization; condition; update statement)
{
Statement
}
Note:
First initialized content is executed only one time. Then the test expression is executed, if the test expression is false then the loop gets terminated.
Example-
class Student
{
Public static void main(String args[])
{
int i=7;
for(i=1; i<8; i++)
{
System.out.println(“i”);
}
}
}
Output-
1 2 3 4 5 6 7.
While loop;-
Syntax-
Initialization;
While(testcondition)
{
Statement inside the body is executed
}
Example-
class Student
{
public static void main
{
int i=2;
while(i<=9)
{
System.out.println(i);
i++;
}
}
}
Output-
2 3 4 5 6 7 8 9.
Do-while;-
The do-while loop is similar to the while loop. The body of do while loop is executed at least one. Only, the test expression is evaluated.
Syntax-
do
{
// statements inside the body of the loop
}
while (testExpression);
Example-
class Student
{
public static void main(String args[])
{
int i=12;
do
{
System.out.println(i);
i++;
}
while(i<=18)
}
}
Output-
12 13 14 15 16 18
Khushi Singh
21-Feb-2025Loops serve multiple functions in Java to execute code sequences repeatedly until specified conditions become untrue. The Java programming language includes three distinct looping structures which are referred to as for loop, while loop, and do-while loop. Loops operate for particular needs according to different circumstances.
1. For Loop: The For Loop helps programmers execute operations exactly when the iteration count remains known in advance. The loop includes three fundamental elements that include variable initialization followed by the condition test before moving to variable update through increment/decrement. The execution sequence of the loop will continue while the condition test remains valid.
2. While Loop: The While Loop serves purposes when the exact number of iterations becomes known during program execution. The loop will initiate execution only when the condition proves true both for entering and proceeding inside the loop. The loop will remain inactive when the initial condition evaluation results in falseness.
3. Do-While Loop: A Do-While Loop functions like a while loop yet executes at least once although its condition remains false. The loop investigates the condition only after completing its body. This condition provides valuable functionality whenever you require the code block to execute at minimum once despite the evaluated condition.
A program determines which loop type to use depending on its needs. Programmers should use the for loop when the number of iterations is known ahead of time but should use the while loop for unknown or variable iteration quantities and depend on the do-while loop when they need block code execution at minimum once.