The most common and basic type of loop is the numerated for loop. This is the loop that starts at a value, increments by a certain amount (almost always 1), until it hits a certain target, running code that many times. The most common syntax for this is the one found in C/C++/Java/JavaScript:
for (int i = 0; i < 5; i++) { // In JavaScript, replace 'int' with 'let'
print(i); // Print function is different for every language
}
This will result in the following output:
xxxxxxxxxx
> 0
> 1
> 2
> 3
> 4
To go from 1 to 5, set i to 1 initially, and make the end condition i <= 5
, rather than i < 5
.
This is often used to iterate through an array, like so:
x// Java Example
int myarr[] = {1, 2, 3, 4, 5};
// arrays start at 0, so our loop goes from 0-4 (myarr.length is 5)
for (int i = 0; i < myarr.length; i++) {
int current_value = myarr[i];
System.out.println(current_value); // Java print function
}
This will output:
xxxxxxxxxx
> 1
> 2
> 3
> 4
> 5
a while loop keeps running the code body until a certain condition is met.
xxxxxxxxxx
-- Example in Lua
local num = 0
while num < 5 do
print(num)
num = num + 1
end
Some languages will have specific ways to iterate through collections like arrays. These are normally special functions called iterators.
Since they are language specific, they look different in every language.
A few examples include:
Python:
xxxxxxxxxx
mylist = [1, 2, 3, 4, 5]
for num in mylist:
print(num)
Rust:
xxxxxxxxxx
let myvec: Vec<i32> = vec![1, 2, 3, 4, 5];
for num in myvec {
println!("{num}");
}
Lua:
xxxxxxxxxx
local mytable = {1, 2, 3, 4, 5}
for i, num in pairs(mytable) do
print(num)
end
Java/C++:
xxxxxxxxxx
int myarr[] = {1, 2, 3, 4, 5};
for (int x : myarr) {
// Java
System.out.println(x)
// C++
std::cout << x << std::endl;
}