Language-specific implementation
In MATLAB:
In Rust, we can annotate our loops with labels:
Range-based loops
For a data structure with a given size, we often iterate through each element in the structure, i.e.,:
Range-based loops are able to iterate through in a succinct way, without us needing to access the size()
method. For the same functionality, we use:
- In C++, we use
for (auto i : list)
, which uses iterators. - In Python/Rust, we use
for i in list
- In JavaScript, we use
for (let i of list)
Under the hood
In Assembly languages, we make use of conditionals and branches to determine where to go. For example, take this program in C:
In Nios II:
Broadly speaking for a program like this:
We can divide these into a few distinct steps, all of which can be executed with several instructions:
- Everything before the loop
- Initial computations
i = 0
- Check the condition
i < 5
- Body of the loop
sum += a[i]
- Post-body computation
i++
- Then we return to the condition; if false we continue to whatever is after the loop