Iteration Statements(LOOPS)
- If we want to execute group of statements repeatedly then we should go for iteration statements.
- There are three types of iteration statements in java language
- For
- While
- Do-while
For-Loop :
In Java, a for
loop is a control flow statement that allows you to repeatedly execute a block of code a specified number of times. The general syntax of a for
loop in Java is:
FOR Syntax:
For (exp1, exp2, exp3)
{
Body;
}
Example:-
For (initialization; condition; increment/decrement)
{
Body;
}
Initialization part:
- Inside the for loop initialization part is optional.
- Instead of initialization it is possible to take any number of System.out.println(“hello”);also and each and every statement is separated by camas(,).
- Initialization part it is possible to take the single initialization it is not possible to take the more than one initialization.
Conditional part:-
- Inside the for loop conditional part is optional.
- If we are not taking any condition then compiler places the true value.
- The condition is always must return Boolean(true/false) values only.
Increment/Decrement:-
- Inside the for loop increment/decrement session is optional.
- Inside of increment/decrement it is possible to take the any number of System.out.println(“abc”); also and each and every statement is separated by camas(,).
While-Loop
In Java, a while
loop is a control flow statement that allows you to repeatedly execute a block of code as long as a specified condition is true. The general syntax of a while
loop in Java is:
Syntax:-
While(condition)
{
Body;
}
EXAMPLE:
int i = 1;
while (i <= 5) {
System.out.println(i);
i++;
}
In this example:
- Condition:
i <= 5
specifies that the loop will continue as long asi
is less than or equal to 5. - Code Block:
System.out.println(i);
prints the value ofi
to the console, andi++;
increments the value ofi
by 1 after each iteration.
The output of this loop would be:
1 2 3 4 5
DO-WHILE
In Java, the do-while
loop is a control flow statement that is similar to the while
loop, with one key difference: the do-while
loop guarantees that the code block is executed at least once before checking the loop condition. The general syntax of a do-while
loop in Java is:
Sysntax:-
Do
{
Body of loop
}
While (condtion);
- If we want to execute the loop body at least one time then we should go for do-while statement.
- In the do-while first body will be executed then only condition will be checked.
- In the do-while the while must be ends with semicolon otherwise we are getting compilation error.
- Do is talking the body and while is talking the condition and the condition must be Boolean condition.