Loops Flashcards

(11 cards)

1
Q

What is the structure of a basic for loop in Java?

A

A for loop has three components: initialization, condition, and iteration
for (int i = 0; i < 10; i++) {
System.out.println(i);
}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

How do you loop through an array using a for loop in Java?

A

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]);
}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

: What is a for-each loop in Java and how does it work?

A

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 well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

How do you use nested for loops to iterate over a 2D array?

A

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]);
}
}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

What is a while loop in Java and when is it used?

A

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 well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

How does a do-while loop differ from a while loop?

A

A do-while loop executes the block of code at least once.

int i = 0;
do {
System.out.println(i);
i++;
} while (i < 5);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

What does the break statement do in a loop?

A

The break statement immediately exits the loop.

for (int i = 0; i < 10; i++) {
if (i == 5) break;
System.out.println(i);
}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

: What does the continue statement do in a loop?

A

The continue statement skips the current iteration.

for (int i = 0; i < 5; i++) {
if (i == 2) continue;
System.out.println(i);
}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

How do you create an infinite loop in Java?

A

Use a condition that always evaluates to true.

while (true) {
System.out.println(“This is an infinite loop”);
}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

How do you loop backwards in a for loop

A

Start from the last index and decrement the loop counter.

for (int i = 5; i >= 0; i–) {
System.out.println(i);
}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q
A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly