1-D arrays: store, index, and traverse · Arreglos 1-D: almacenar, indexar y recorrer
Many values in one box
- An array holds many values of the same type in order.
- Until now one variable held one value. An array holds a whole list.
- For example, the test scores of a class can live in one
intarray.
Muchos valores en una sola caja
- Una matriz contiene muchos valores del mismo tipo en orden.
- Hasta ahora, una variable almacenaba un solo valor. Una matriz contiene una lista completa.
- Por ejemplo, las calificaciones de un examen de una clase pueden estar en una sola
intmatriz.
Make an array with values
- If you know the values, list them in curly braces
{ }. - The type is the element type plus
[], likeint[]. - Java counts how many values you gave and makes the array that size.
Crear una matriz con valores
- Si conoces los valores, escríbelos entre llaves
{ }. - El tipo es el tipo de elemento más
[], comoint[]. - Java cuenta cuántos valores diste y crea la matriz con ese tamaño.
public class Main {
public static void main(String[] args) {
int[] scores = {90, 80, 70};
System.out.println(scores[0]); // 90
System.out.println(scores[2]); // 70
}
}
Index positions
- Each value has an index (its position). Indexes start at 0.
- So the first value is
scores[0], the second isscores[1], and so on. - You can also change a value:
scores[1] = 85;.
Posiciones de índice
- Cada valor tiene un índice (su posición). Los índices comienzan en 0.
- Así que el primer valor es
scores[0], el segundo esscores[1], y así sucesivamente. - También puedes cambiar un valor:
scores[1] = 85;.
public class Main {
public static void main(String[] args) {
int[] scores = {90, 80, 70};
scores[1] = 85; // change the middle value
System.out.println(scores[1]); // 85
}
}
Make an empty array
- Use
new int[n]to make an array ofnvalues. - Every
intslot starts at 0 automatically. - Then you fill the slots one by one.
Crear una matriz vacía
- Usa
new int[n]para crear una matriz denvalores. - Cada ranura de
intcomienza automáticamente en 0. - Luego llenas las ranuras una por una.
public class Main {
public static void main(String[] args) {
int[] nums = new int[3]; // {0, 0, 0}
nums[0] = 5;
nums[1] = 6;
System.out.println(nums[0] + " " + nums[1] + " " + nums[2]); // 5 6 0
}
}
.length
array.lengthtells you how many values the array has.- Note: no parentheses — it is
scores.length, notscores.length(). - The last valid index is always
length - 1.
.length
array.lengthte dice cuántos valores tiene la matriz.- Nota: sin paréntesis — es
scores.length, noscores.length(). - El último índice válido siempre es
length - 1.
public class Main {
public static void main(String[] args) {
int[] scores = {90, 80, 70};
System.out.println(scores.length); // 3
System.out.println(scores[scores.length - 1]); // 70 (last value)
}
}
Traverse with a for loop
- To visit every value, loop the index from
0up tolength - 1. - Use
i < array.lengthas the stop test. - Below we add up every value.
Recorrer con un bucle for
- Para visitar cada valor, itera el índice desde
0hastalength - 1. - Usa
i < array.lengthcomo prueba de parada. - A continuación sumamos cada valor.
public class Main {
public static void main(String[] args) {
int[] scores = {90, 80, 70};
int total = 0;
for (int i = 0; i < scores.length; i++) {
total = total + scores[i];
}
System.out.println(total); // 240
}
}
Enhanced for loop
- The enhanced for (or "for-each") visits each value directly.
- Read it as: "for each
int vinscores". - Use it when you only need the values, not the index.
Bucle for mejorado
- El bucle for mejorado (o "for-each") visita cada valor directamente.
- Léalo como: "para cada ⟨
int v⟩ en ⟨scores⟩". - Úsalo cuando solo necesitas los valores, no el índice.
public class Main {
public static void main(String[] args) {
int[] scores = {90, 80, 70};
int total = 0;
for (int v : scores) {
total = total + v;
}
System.out.println(total); // 240
}
}
Common mistakes
a.lengthhas no(); valid indexes run0toa.length - 1.- Going out of range throws ArrayIndexOutOfBoundsException.
Errores comunes
- Un ⟨
a.length⟩ no tiene ⟨()⟩; los índices válidos van de ⟨0⟩ a ⟨a.length - 1⟩. - Excederse del rango lanza ArrayIndexOutOfBoundsException.
Now you try
- Some tasks print a result; others complete a method the Harness calls.
- Remember: indexes start at 0, and the last index is
length - 1. - Press Run to compile, then Check answer.
Ahora tú practica
- Algunas tareas imprimen un resultado; otras completan un método que llama el Harness.
- Recuerda: los índices comienzan en 0, y el último índice es ⟨
length - 1⟩. - Presiona Run para compilar, luego Check answer.
A 1-D array, indexed · Un arreglo 1-D, indexado
An array stores values in order; reach one with a[i]. · Un arreglo almacena valores en orden; accede a uno con a[i].
The array nums is already filled. Use a loop to add up all its values and print the total on one line. For {4, 8, 15, 16, 23, 42} the output is 108. · El arreglo nums ya está lleno. Usa un bucle para sumar todos sus valores e imprime el total en una línea. Para {4, 8, 15, 16, 23, 42} la salida es 108.
Click Run to see the output here. · Haz clic en Ejecutar para ver la salida aquí.
Complete sum(int[] a) so it returns the sum of all values in the array. An empty array should return 0. The checker calls it with several arrays. · Completa sum(int[] a) para que devuelva la suma de todos los valores del arreglo. Un arreglo vacío debe devolver 0. El verificador lo llama con varios arreglos.
Click Run to see the output here. · Haz clic en Ejecutar para ver la salida aquí.
Complete doubleAll(int[] a). It does not return anything. Instead it changes the array in place so every value becomes twice as big. {1, 2, 3} becomes {2, 4, 6}. · Completa doubleAll(int[] a). No devuelve nada. En su lugar, modifica el arreglo in situ para que cada valor se duplique. {1, 2, 3} se convierte en {2, 4, 6}.
Click Run to see the output here. · Haz clic en Ejecutar para ver la salida aquí.