Looping Over Arrays
for and foreach.
Why Loop?
Arrays often hold many values, and you rarely want to type each index by hand. A loop repeats an action for every element automatically.
This lets you print, sum, or check all values with just a few lines.
The for Loop
A for loop uses a counter. Start it at 0 and continue while the counter is less than Length, increasing by one each time.
The counter doubles as the index, so you can access each element.
int[] nums = { 10, 20, 30 };
for (int i = 0; i < nums.Length; i++)
{
Console.WriteLine(nums[i]);
}All lessons in this course
- Declaring Arrays
- Indexing and Length
- Looping Over Arrays
- Multidimensional Arrays