Lecture 12 - Repetition
Lecture 12 - Repetition
● 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 syntax of a while loop in Java is as follows:
while (condition) {
// code block to be executed
}
int i = 1;
while (i <= 5) {
System.out.println(i);
i++;
}
● In this example, the condition i <= 5 is true for the first five iterations of the
loop, so the code block inside the loop is executed five times.
● The loop terminates when i becomes 6, at which point the condition is false
and the loop exits.
1
Do-while loop
● A do-while loop is a control flow statement that allows you to repeatedly
execute a block of code at least once and then as long as a specified
condition is true.
● The syntax of a do-while loop in Java is as follows:
do {
// code block to be executed
} while (condition);
int i = 1;
do {
System.out.println(i);
i++;
} while (i <= 5);
2
For loop
● A for loop is a control flow statement that allows you to repeatedly execute a
block of code a fixed number of times.
● The syntax of a for loop in Java is as follows:
● In this example, i is initialized to 1, and the condition i <= 5 is true for the first
five iterations of the loop.
● The code block inside the loop is executed five times, and i is incremented
by 1 after each iteration.
3
● The loop terminates when i becomes 6, at which point the condition is false
and the loop exits.
● You can use a for loop to iterate over the elements of an array or a collection
as well.
● In this case, the initialization statement initializes a loop variable that
represents the index of the element, and the condition checks if the index is
less than the length of the array or the size of the collection.
● The update statement increments the index by 1 after each iteration. Here's
an example that prints the elements of an array:
● In this example, i is initialized to 0, and the condition i < arr.length is true for
the first five iterations of the loop.
● The code block inside the loop is executed five times, and i is incremented
by 1 after each iteration. The loop terminates when i becomes 5, at which
point the condition is false and the loop exits.
Nested loop
● A nested loop is a loop inside another loop.
● This means that the code inside the outer loop will execute multiple times,
with the inner loop executing completely each time the outer loop runs.
● The inner loop can itself contain other loops and conditional statements.
● The basic syntax of a nested loop is as follows:
4
}
● In this example, the outer loop iterates from 1 to 10, and the inner loop also
iterates from 1 to 10.
● The code block inside the inner loop prints the product of the loop variables i
and j, followed by a space.
● The code block inside the outer loop then prints a newline character to start
a new line.