12
C# Loops - Part 1: Loop Types & For Loop Tutorial
Ok so we've covered a lot of the basics already, and here's yet another core feature of any programming language; the Loop.
Why write code multiple times, when you can just repeat the same code however many times you want it to. Sounds simple right, well it is.
There are a few ways of writing loops in C#, the
- for loop
- for each loop
- do..while loop
- while loop
The for loop is one of the most common loops you'll probably see within C# code.
The for loop repeats code a predefined number of times. That behaviour is possible because the loop counts from one value to the next. This way we can perform calculations and loop over a list or array.
It combines three common loop actions together: declare and initialise the loop variable, check the loop condition before each loop cycle, and update the loop variable after each iteration
Lets take a look at a very easy counting example:
![](https://res.cloudinary.com/practicaldev/image/fetch/s--3D-jDIW1--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/n975714q8c67nhu7ymbt.png)
Explanation:
![](https://res.cloudinary.com/practicaldev/image/fetch/s--vSM_iEoQ--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5oz733ksfbpqc797am43.jpg)
The loop variable is a variable assigned to the loop, and is used simply as a number, to increment and move the loop along.
The loop condition, is the condition that is checked each iteration, if the condition is met the code is executed.
The loop increment, after the code is executed the final code is executed. You can either increment it or decrease the variable, depending if you're iterating in reverse or not.
Fact: - the "++" operator you see within the code is a way of writing increase by one in C# (and many other languages). Its just an easier way of saying "i = i + 1;". I've kept counter = counter + 1. To show both ways of doing it. You can also use "_ --_" to decrease by 1.
You could also use "+=" and "-=" operators to decrease and increase the value by more than 1. Here, we increase the counter by 3 each repetition, and output the letters each time.
![](https://res.cloudinary.com/practicaldev/image/fetch/s--DLUSL6uX--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ck0t4hu2ul5pwh58bjqy.png)
So when would you use a loop in the real world? There are a few uses, but the common is looping through either an array of numbers, or words. The other most common is looping through a collection / list of objects, and retrieving some information and doing something with it.
Lets look at an example:
Address Book
using System;
using System.Collections.Generic;
public class Address {
public string Name { get; set; }
public string AddressLineOne {get;set;}
public int HouseNumber { get; set; }
public string PostCode { get; set; }
public string Telephone {get;set;}
}
public class Program
{
public static void Main()
{
//create a list of address objects
var addressBook = new List<Address>{
new Address{
Name = "Grant",
AddressLineOne = "Developer Avenue",
HouseNumber = 1,
PostCode = "DV19 8EP",
Telephone = "0102919 93020-92019"
}, new Address{
Name = "Bill",
AddressLineOne = "Developer Avenue",
HouseNumber = 19,
PostCode = "DV19 8EP",
Telephone = "0102919 93020-92019"
}, new Address{
Name = "Rebecca",
AddressLineOne = "Developer Avenue",
HouseNumber = 4,
PostCode = "DV19 8EP",
Telephone = "0102919 93020-92019"
}, new Address{
Name = "Amy",
AddressLineOne = "Rower Avenue",
HouseNumber = 1,
PostCode = "DV19 8EP",
Telephone = "0102919 93020-92019"
}, new Address{
Name = "Joe",
AddressLineOne = "Olympic Drive",
HouseNumber = 1,
PostCode = "DV19 10E",
Telephone = "0102919 93020-92019"
}
};
for(var i =0; i < addressBook.Count; i++)
{
var name = addressBook[i].Name;
Console.WriteLine(name);
}
}
}
Unlike other examples, I've included the code in a code block to allow you easy copy and paste -- this is how I will be doing it from now for larger code examples. The photo images, are more to get you thinking and writing out the code yourself (as I find its a good way to learn).
So, what have we done? - I've created a really simple class to hold address details. We've then utilised this class within our Main Console program, and created a list of address items. We've done this by declaring a new List<Address>. The angle brackets define the Type of list we're creating, so in this case a list of Address objects.
We then use our for loop, to iterate through the items. Rather than before where we've set an arbitrary number of times we want the loop to run, this time we're doing this by setting the condition to
i < addressBook.Count
this will return the number of elements in the list (5). Since we've set our "loop variable" to 0, we use the less than operator, on the count. As it will still repeat 5 times, e.g 0, 1, 2, 3, 4 < 5.
If you were to set i = 1; The condition would need to be
i <= addressBook.Count (less than or equal to).
Ok so following all that? Now we get to real usage of the for loop, the index accessor. We can access a particular object within the addressBook by using an index. This is shown here
var name = addressBook[i].Name;
Every item in an array, collection or list in C# is given an index. Think of this like a page index of a book. Its a reference to that item in the list. Indexes on arrays and lists in C# all start at 0, you'll hear the phrase "zero-based".
As a result, in your mind you would deduct one from each pointer in the list, e.g first item in the list would be index 0, 2nd 1, 3rd 2 and so on.
Therefore, the easiest way to loop through items, and access them in a for loop is to utilise the loop variable "i", since i = 0, and is being incremented itself each time round the loop.
We access the item in the list, using the "[number]" syntax. So we take the name of the list variable, then tell it we want the item at index i then we want the Name property
addressBook[i].Name;
we then print out "Name: name"
Try it out now in your own, and change some of the address details, and run to see the new output. Try changing the .Name property for another property.
Up next ---> For Each Loop
12