Bucles for sobre rangos y elementos
Itere sobre secuencias y pares de índices.
Bucles for sobre rangos y elementos es una lección gratuita de Zig Academy en CoddyKit. Esta es la lección 3 de 4. Puedes leer la lección completa abajo gratuitamente — luego la practicas en el navegador con un editor de código integrado y un tutor de IA 24/7. Forma parte de la ruta de aprendizaje de Zig Academy, y tu progreso se sincroniza en la web y la app de CoddyKit. El curso de Zig Academy incluye 4 lecciones en total.
Partes de esta lección aún no han sido traducidas y se muestran en inglés.
Iterate with for
A for loop walks through the elements of a slice or array, handing you each item in turn. No manual index needed. 🚶
for (names) |name| {
std.debug.print("{s}\n", .{name});
}The Capture in Pipes
The name between pipes is the capture. On each pass it binds to the current element, giving you a clean, readable loop body.
Capturing by Reference
Prefix the capture with * to get a pointer to each element. That lets you modify items in place rather than copying them.
for (scores) |*s| {
s.* += 1;
}Getting the Index
Add a second sequence to pair items with an index. Zig walks both together, giving you the value and its position.
for (items, 0..) |item, i| {
std.debug.print("{}: {}\n", .{ i, item });
}0.. Is an Index Sequence
The 0.. form produces indices that match the length of the items. It is not a separate array, just a counter walked in lockstep.
Looping a Fixed Count
To repeat a set number of times, iterate over a range like 0..count. The capture holds the current number on each pass.
for (0..3) |n| {
std.debug.print("step {}\n", .{n});
}Ranges Are Half-Open
A range like 0..5 includes 0 but stops before 5, giving exactly five values. This half-open style matches slice lengths perfectly.
Iterating Two Slices
Pass several slices to walk them in parallel. Zig requires them to share the same length, then yields one element from each per pass.
for (keys, values) |k, v| {
put(k, v);
}break and continue Apply
Inside a for loop you can use break to exit early and continue to skip to the next item, just like in a while loop.
for as an Expression
A for can yield a value too. break returns a result, while an else clause supplies the value if the loop completes without breaking.
const idx = for (items, 0..) |x, i| {
if (x == target) break i;
} else null;Pick for or while
Reach for for when you have a sequence to walk. Choose while when looping depends on a condition rather than a collection.
Quick Check
You need both each item and its index in one for loop. Which header does that?
Recap
You ran for loops: capturing items, by-reference edits, indices with 0.., counting ranges, parallel slices, and the value-returning form. 🎯
Preguntas frecuentes
¿La lección «Bucles for sobre rangos y elementos» es gratis?
Sí — el texto completo de «Bucles for sobre rangos y elementos» es gratis para leer aquí en la web. Para practicarla de forma interactiva (editor de código integrado y tutor de IA 24/7) y desbloquear el resto del curso de Zig Academy, actualiza a CoddyKit PRO. El curso de Zig Academy incluye 4 lecciones en total.
¿Qué aprenderé en «Bucles for sobre rangos y elementos»?
Itere sobre secuencias y pares de índices. Practicas Zig Academy con código real que ejecutas directamente en el navegador, y un tutor de IA 24/7 responde tus preguntas mientras trabajas en la lección.
¿Necesito experiencia previa para empezar Zig Academy?
No se requiere experiencia previa. Zig Academy en CoddyKit está estructurado para principiantes hasta estudiantes avanzados, así que puedes empezar aquí o desde el inicio y avanzar a tu ritmo. Esta es la lección 3 de 4.
¿Cuánto tiempo toma la lección «Bucles for sobre rangos y elementos»?
La mayoría de las lecciones de CoddyKit toman alrededor de 5–10 minutos. Cada una es compacta e interactiva, así que avanzas constantemente y retomas exactamente por donde dejaste en la web y la app.
¿Puedo escribir y ejecutar código en esta lección de Zig Academy?
Sí. Cada lección de Zig Academy incluye un editor de código integrado, así que escribes y ejecutas código real directamente en tu navegador y obtienes retroalimentación instantánea de IA — sin configuración local necesaria.
Todas las lecciones de este curso
- if como sentencia y expresión
- Bucles while y expresiones continue
- Bucles for sobre rangos y elementos
- break, continue y bucles etiquetados