All Flashcards
What are the steps to traverse an array forwards using a for loop?
Initialize index to 0, check if index is less than array length, access element at index, increment index.
What are the steps to traverse an array in reverse using a for loop?
Initialize index to array.length - 1, check if index is greater than or equal to 0, access element at index, decrement index.
What are the differences between using a for loop and a while loop for array traversal?
For loop: More concise, easier to read iteration count. While loop: More flexible, requires manual index management.
What does the following code output?
java
int[] arr = {1, 2, 3};
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
1 2 3
What does the following code output?
java
int[] arr = {5, 10, 15};
for (int i = arr.length - 1; i >= 0; i--) {
System.out.print(arr[i] + " ");
}
15 10 5
Identify the error in the following code:
java
int[] arr = new int[5];
for (int i = 0; i <= arr.length; i++) {
arr[i] = i;
}
ArrayIndexOutOfBoundsException. The loop should iterate while i < arr.length.
What does the following code output?
java
int[] arr = {1, 2, 3, 4, 5};
for (int i = 2; i < 4; i++) {
System.out.print(arr[i] + " ");
}
3 4
What does the following code output?
java
int[] arr = {5, 10, 15, 20};
for (int i = 0; i < arr.length; i++) {
arr[i] += 5;
System.out.print(arr[i] + " ");
}
10 15 20 25
What does the following code output?
java
int[] arr = {1, 2, 3, 4, 5};
for (int i = 0; i < arr.length; i++) {
if (arr[i] % 2 == 0) {
System.out.print(arr[i] + " ");
}
}
2 4
What does the following code output?
java
int[] arr = {1, 2, 3, 4, 5};
for (int i = 0; i < arr.length; i++) {
arr[i] = arr[i] * 2;
}
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
2 4 6 8 10
What does the following code output?
java
int[] arr = {1, 2, 3, 4, 5};
int sum = 0;
for (int i = 0; i < arr.length; i++) {
sum += arr[i];
}
System.out.println(sum);
15
What does the following code output?
java
int[] arr = {1, 2, 3, 4, 5};
for (int i = 0; i < arr.length; i++) {
if (arr[i] > 2) {
System.out.print(arr[i] + " ");
}
}
3 4 5
What does the following code output?
java
int[] arr = {1, 2, 3, 4, 5};
int product = 1;
for (int i = 0; i < arr.length; i++) {
product *= arr[i];
}
System.out.println(product);
120