Programming in C#, Part 4: Arrays, Lists, & Loops (Oh My!)

So we’re on to our next important subject, arrays and lists, along with loops. These are things you’ll use a ton. You might already be familiar with these concepts. Stuff to google or research outside of this lesson will be, as always, in bold.

Arrays and Lists

This tutorial is just full of super important information, including arrays (and lists). Arrays give you a way to store multiple variables into one variable, and then access them with an numerical index. One thing that’s important to remember for arrays (and pretty much everything in programming having to do with numbers) is that they don’t start at 1, they start at 0.

Arrays

So let’s see an example, when we made an array we simply add [] after the variable type. There are different ways to assign values to an array, here are a few.

string[] characters = new string[3]; //This doesn't have any data though
string[] characters = new string[] { "Bob", "Cory", "Rachel" };
string[] characters = { "Bob", "Cory", "Rachel" };

So here we’re making an array of different character names. Note the first one doesn’t actually have any values inside of it, we’ve just made an array with 3 spots without any actual data inside. I’ll show you below when we talk about for loops how we might fill those out.

It’s important to note that an array is a fixed size, so once you give it a size of 3, it will always be a size of 3 and you can’t really change that. We don’t define a size for the bottom two, because it’s getting the size from the number of entries we put. We could also define a size on the 2nd method, and we would be forced to put that many values.

If you want to change a value, you can access that value and set it like a variable like so.

characters[0] = "No longer Bob";

Lists

So the way that lists differ is that they don’t have a fixed size, you can add new values whenever you like. There are also some differences in the way their memory is stored, arrays data is stored in contiguous blocks of memory. You can google more about these differences if you’re curious.

So unlike an array, when you define a list you cannot just give it values instantly, you must create a new list and add values.

List characters = new List();
characters.Add("Bob");
characters.Add("Cory");
characters.Add("Rachel");

The way you access a value to change it is the same as an array. However in a list you can also remove values with .Remove() and .RemoveAt().

Arrays and lists have other useful ways you can manipulate and change them, which you can find out about with google.

Common Errors:

Just a quick note, one of the most common errors I see people confused by is when they get an Index out of range exception. This means lets say you have an array like we do above, with our three characters. Remembering that arrays start at 0, we would access them with characters[0], characters[1], and characters[2]. If you try to access any negative numbers, or characters[3] or above, you’ll get that error because that index doesn’t exist.

One potential cause is with our loops, arrays have a .Length property that tells you how big it is (for lists it’s .Count). Well if I used .Length, that would give me 3, so if someone wanted to get the last value, they might try and do characters[characters.Length], but that wouldn’t work because 3 is not a valid index. You’d need to do .Length - 1, so that’s an important thing to keep in mind.

Loops

Ah, loops. Loops are pretty much one of the most important things you’ll use, it’s hard to get around using them. They allow you to do the same thing over, and over; so you don’t have to type it out. There are quite a few different types of loops, probably some I don’t even know about. We’ll go over some of the more important and commonly used ones.

While Loops

While loops are the most basic kind of loop. Similar to an if statement, they take in a boolean value which determines if that loop should continue looping or if it should stop and continue on with the code. So for example you could do:

bool keepGoing = true;
while(keepGoing)
{
    Console.WriteLine("We're running!");
    if(Console.ReadLine() == "STOP")
    {
        keepGoing = false;
    }
}

In this case the console would display “We’re running!” then check for input, if you give it anything other than “STOP” it will keep displaying keep running, until the program is stopped or you give it that value. This is a similar concept to how a general game loop would work.

Do Whiles

Do whiles are almost exactly like whiles, the only difference is that they will run whatever is inside at least once before checking the condition.

do
{
    Console.WriteLine("We're running!");
} while(Console.ReadLine() != "STOP");

For Loops

Man oh man, for loops are the best. So imagine you wanted to go all the way through your arrays values and change them to something. Well individually going to each value and changing it is a pain, plus if you change that array or lists size you could potentially run into errors. So with our knowledge of while loops we might do something like this.

string[] myArray = { "Value", "Value", "Value" };
int i = 0;
while(i < myArray.Length)
{
    myArray[i] = myArray[i] + i; //Changes to have its index in its name
    i++; //Quick way to add one to an int
}

Which works, I guess. But… there’s a better way! There is a special loop made just for this, called the for loop. This loop is formatted like so.

string[] myArray = { "Value", "Value", "Value" };
for(int i = 0; i < myArray.Length; i++)
{
    myArray[i] = myArray[i] + i; //Changes to have its index in its name
}

So a quick summary of this loop, it’s doing exactly what we did before, but much more condensed and clean. Basically within the for loops parenthesis we can make statements that will only exist within the scope of our loop. So outside the loop you wont be able to use the variable i, unlike with our while loop. So you’ll notice the first bit runs once, and makes the variable i, then every time our loop runs it checks the middle statement to see if its true. If it is, we continue and run the last statement.

For loops are super powerful, and can do some awesome things if used right and can be especially useful dealing with arrays and lists.

Foreach Loops

These are similar to for loops, except we don’t use numbers. We simply tell the program we want to go through the list, and use a variable to represent our current index we’re at, like so.

string[] characters = { "Bob", "Cory", "Rachel" };
foreach(string person in characters)
{
    person = person + " Smith"; //Gives everyone the last name Smith
}

Which makes it easier to do some things. You’ll notice we used the in keyword, it’s pretty simply to use if you wanted to look it up.

Extra Practice

Here’s your optional practice! If you choose to accept this word document, good luck, keep your google at the ready, and dive right in.

File: CSharpTutorials2

Next Time

We’re talking all about classes, and it’s a doozy!

Support

Are you having trouble with understanding this tutorial? Please feel free to contact me via email at KoseckCory@gmail.com or message me on discord at 7ark#8194.

I would love to get feedback from people so I can add and improve these tutorials overtime. Letting me know what you’re confused about will let me update the tutorials to be more concise and helpful.

If you’re interested in supporting me personally, you can follow me on Twitter or Instagram. If you want to support me financially, I have a Patreon and a Ko-fi.

2 comments on “Programming in C#, Part 4: Arrays, Lists, & Loops (Oh My!)Add yours →

Leave a Reply

Your email address will not be published. Required fields are marked *