CL-9 CH-9 (Iterative Constructs in Java)
CL-9 CH-9 (Iterative Constructs in Java)
Chapter- 9
Iterative Constructs in Java
Java is a widely-used programming language known for its versatility and
ability to handle complex tasks. One of the fundamental concepts in Java
programming is the use of iterative constructs that allows us to repeat a set
of instructions multiple times. In this section, we will explore the three
main iterative constructs in Java: the "for" loop, the "while" loop, and the
"do-while" loop. We will provide detailed explanations, along with full
Java programs, comments, and output examples, to help you understand
how to use these constructs effectively in your coding endeavours.
1. Java for Loop
The "for" loop in Java is used when you know in advance how many times
you want to repeat a set of instructions. It consists of three parts:
initialization, condition, and increment/decrement. Let's break down each
part with a simple example:
ForLoopExample.java
1. public class ForLoopExample
2. {
3. public static void main(String[] args)
{
4. // Initialization: Start from 1
5. // Condition: Continue while i is less than or equal to 5
6. // Increment: Increase i by 1 in each iteration
7. for (int i = 1; i <= 5; i++)
{
8. System.out.println("Iteration " + i);
}
}
}
Output:
Iteration 1
Iteration 2
Iteration 3
Iteration 4
Iteration 5
Iteration 1
Iteration 2
Iteration 3
Iteration 4
Iteration 5
Number is 5
Number is 4
Number is 3
Number is 2
Number is 1
Output:
Iteration 1
Iteration 2
Iteration 3
Iteration 4
Java continue statement: It is used to skip the rest of the current iteration
and proceed to the next iteration of the loop. Here's an example:
ContinueStatementExample.java
1. public class ContinueStatementExample
2. {
3. public static void main(String[] args)
{
4. for (int i = 1; i <= 5; i++)
{
5. if (i == 3)
{
6. continue; // Skip iteration when i is 3
7. }
8. System.out.println("Iteration " + i);
9. }
}
}
Output:
Iteration 1
Iteration 2
Iteration 4
Iteration 5