3 min readβ’december 30, 2022
Peter Cao
Milo Chang
Peter Cao
Milo Chang
for (int i = 0; i < array.length; i++) {
do something with array[i]
}
int[] arrayTwo = new int[10] {
for (int i = 0; i < array.length; i++) {
arrayTwo[i] = i;
}
}
for (int i = array.length - 1; i >= 0; i--) {
do something with array[i]
}
Different Start Index
i = 1
and end at i = array.length - 1
. Our for loop would be written as:for (int i = 1; i < array.length; i++) {
do something with array[i]
}
Different End Index
array.length - 1
). For this, we start at index i = 0
and end at i = n - 1
. Our for loop would be written as:for (int i = 0; i < n; i++) {
do something with array[i]
}
Subsection
i = 2
and end at i = 6
. Our for loop would be written as:for (int i = 2; i < 7; i++) {
do something with array[i]
}
/** Doubles each element of the array
*/
public static void doubleArray(int[] array) {
for (int i = 0; i < array.length; i++) {
array[i] *= 2; // doubles each individual element
}
}
0
to array.length - 1
, we find the array element at index i and double it."/** Doubles each element of the array
*/
public static void doubleArray(int[] array) {
int i = 0;
while (i < array.length) {
array[i] *= 2; // doubles each individual element
i++;
}
}
10
in an array that only has indices 0
to 9
), you'll get an ArrayIndexOutOfBoundsException
.Β© 2023 Fiveable Inc. All rights reserved.