Which loop is commonly used to iterate through an array in Java?
A
if loop B
do-else loop C
for loop D
switch loop
Analysis & Theory
`for` loop is commonly used to iterate through arrays using an index.
What is the output?
```java
int[] nums = {1, 2, 3};
for(int i = 0; i < nums.length; i++) {
System.out.print(nums[i]);
}```
A
123 B
012 C
111 D
Error
Analysis & Theory
This prints all elements in the array using a standard for loop.
Which loop type automatically accesses each element without using an index?
A
while loop B
for-each loop C
do-while loop D
infinite loop
Analysis & Theory
`for-each` loop iterates over elements directly without needing indexes.
What is the output?
```java
int[] arr = {10, 20, 30};
for(int num : arr) {
System.out.print(num + " ");
}```
A
10 20 30 B
0 1 2 C
10 10 10 D
Error
Analysis & Theory
Enhanced `for` loop directly prints the array elements.
Which of the following is a correct syntax for a `while` loop through an array?
A
while(i < arr) { i++; } B
while(arr.length) { } C
int i=0; while(i < arr.length) { i++; } D
foreach(int i in arr) { }
Analysis & Theory
You need to declare an index and compare it to `arr.length`.
What happens if you forget to increment the loop index while looping?
A
The loop runs normally B
Array resets C
You get a compile-time error D
The loop may run infinitely
Analysis & Theory
If the index is not incremented, the loop condition may always be true, causing an infinite loop.
What is the output?
```java
int[] arr = {1, 2, 3};
int i = 0;
while(i < arr.length) {
System.out.print(arr[i]);
i++;
}```
A
123 B
012 C
321 D
111
Analysis & Theory
A `while` loop prints elements 1, 2, and 3 in order.
Which loop is best for modifying array elements by index?
A
for-each loop B
while loop with no counter C
for loop with index D
switch-case
Analysis & Theory
A `for` loop with an index is ideal when you need to modify array elements.
Can you modify the original array values using a for-each loop?
A
Yes, always B
No, for-each uses a copy of the element C
Only in Java 8 or later D
Yes, if the array is of type double
Analysis & Theory
`for-each` loop gives a copy of the element, so modifying it doesn't affect the array.
What is the output?
```java
String[] fruits = {"Apple", "Banana"};
for(String fruit : fruits) {
System.out.print(fruit + " ");
}```
A
Apple Banana B
Banana Apple C
0 1 D
fruit fruit
Analysis & Theory
Enhanced for-loop prints the values of the array directly.