Loops Flashcards
(11 cards)
What is the structure of a basic for loop in Java?
A for loop has three components: initialization, condition, and iteration
for (int i = 0; i < 10; i++) {
System.out.println(i);
}
How do you loop through an array using a for loop in Java?
Use the array’s length in the loop condition.
int[] arr = {1, 2, 3, 4, 5};
for (int i = 0; i < arr.length; i++) {
System.out.println(arr[i]);
}
: What is a for-each loop in Java and how does it work?
A for-each loop is used to iterate over arrays or collections.
int[] numbers = {10, 20, 30, 40};
for (int num : numbers) {
System.out.println(num);
}
How do you use nested for loops to iterate over a 2D array?
Use one for loop inside another to traverse both dimensions.
int[][] matrix = {{1, 2}, {3, 4}};
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
System.out.println(matrix[i][j]);
}
}
What is a while loop in Java and when is it used?
A while loop repeats a block of code as long as the condition is true.
int i = 0;
while (i < 5) {
System.out.println(i);
i++;
}
How does a do-while loop differ from a while loop?
A do-while loop executes the block of code at least once.
int i = 0;
do {
System.out.println(i);
i++;
} while (i < 5);
What does the break statement do in a loop?
The break statement immediately exits the loop.
for (int i = 0; i < 10; i++) {
if (i == 5) break;
System.out.println(i);
}
: What does the continue statement do in a loop?
The continue statement skips the current iteration.
for (int i = 0; i < 5; i++) {
if (i == 2) continue;
System.out.println(i);
}
How do you create an infinite loop in Java?
Use a condition that always evaluates to true.
while (true) {
System.out.println(“This is an infinite loop”);
}
How do you loop backwards in a for loop
Start from the last index and decrement the loop counter.
for (int i = 5; i >= 0; i–) {
System.out.println(i);
}