For loop: Difference between revisions
From Coderwiki
More actions
new: info, example, iterating a collection |
(No difference)
|
Latest revision as of 10:07, 15 August 2025
A for loop is an iteration structure in code which allows us to loop through a code block and easily increment a variable each time.
It is a form of definite iteration, or count-controlled iteration.
Example
edit edit sourceIn the below C Sharp code, we loop through the numbers 1-5 and print each number to the console:
for (int i = 1; i <= 5; i++)
{
Console.WriteLine(i);
}
Iterating a collection
edit edit sourceIf you instead want to loop over a collection, you can either use a regular for loop and iterate over each index of the collection, or you can use a for each loop to iterate over the elements themselves.
See: For each loop