1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
All Flashcards
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
What is array traversal?
Accessing every value in an array.
What is forward traversal?
Accessing array elements from the beginning to the end.
What is reverse traversal?
Accessing array elements from the end to the beginning.
What is a limited traversal?
Accessing only a portion of elements in the array.
What is ArrayIndexOutOfBoundsException?
An error when trying to access an index that does not exist.
Why are for loops common for array traversal?
They provide a concise way to control the iteration and number of times the loop occurs.
How do you access the first element of an array?
Using index 0.
How do you access the last element of an array?
Using index array.length - 1.
What is the purpose of array.length?
Returns the number of elements in the array.
What is the role of the index variable in array traversal?
The index variable keeps track of the current position in the array during traversal.
What happens if you try to access array[-1]?
It will result in an ArrayIndexOutOfBoundsException.