Tutorial by Examples

void main() { import std.stdio : writeln; int[] arr = [1, 3, 4]; for (int i = 0; i < arr.length; i++) { arr[i] *= 2; } writeln(arr); // [2, 6, 8] }
void main() { import std.stdio : writeln; int[] arr = [1, 3, 4]; int i = 0; while (i < arr.length) { arr[i++] *= 2; } writeln(arr); // [2, 6, 8] }
void main() { import std.stdio : writeln; int[] arr = [1, 3, 4]; int i = 0; assert(arr.length > 0, "Array must contain at least one element"); do { arr[i++] *= 2; } while (i < arr.length); writeln(arr); // [2, 6, 8] }
Foreach allows a less error-prone and better readable way to iterate collections. The attribute ref can be used if we want to directly modify the iterated element. void main() { import std.stdio : writeln; int[] arr = [1, 3, 4]; foreach (ref el; arr) { el *= 2; } ...
void main() { import std.stdio : writeln; int[] arr = [1, 3, 4, 5]; foreach (i, el; arr) { if (i == 0) continue; // continue with the next iteration arr[i] *= 2; if (i == 2) break; // stop the loop iteration } writel...

Page 1 of 1