DEV Community

Cover image for C# Loops - Part 1: Loop Types & For Loop Tutorial
Grant
Grant

Posted on

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.

Kinds of loop in C

There are a few ways of writing loops in C#, the

  • for loop
  • for each loop
  • do..while loop
  • while loop

For 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:

Alt Text

Explanation:

Alt Text

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.

Alt Text

Real World Scenario

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);
        }
    }

}
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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).

Loops and indexes

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;
Enter fullscreen mode Exit fullscreen mode

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;
Enter fullscreen mode Exit fullscreen mode

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

Discussion (1)

Collapse
codeexampler profile image
CodeExampler

c# for loop Statement learn c# for loop Statement in free by codeexampler website