Basics of Programming #13 - Arrays

May 1, 2020 16:24 · 6370 words · 30 minute read otherwise whereas might even called

Alright, it’s time to get right back into it. We’ve gone past the absolute beginners’ stuff, and we’re getting into the slightly more complicated stuff, but, don’t worry, I’ll break everything down and it should all be super clear to follow still. Make sure you remember “for” loops, which look like this – this will count from 0 to technically 9 because it’s always running while “I” is less than 10, it won’t continue to run when I is actually 10, so, this would count from 0 to 9. In this video, we’re going to talk about arrays. Arrays is just a fancy word for a list of items, and we very often use them alongside “for” loops.

00:45 - For example, we would use an array if we want to store a list of names for people visiting a certain place. And that would be an array of strings, because it would be made up of strings. Pretty simple, right? Another example: If we want a list of all the ages of people visiting some place, we would have an array of integers. It’s a list that has numbers in it. Let’s hop over to the code and look at how we would do this in the code, and then we’ll play around with some loops to let the user input lots of names. An array is just like anything else we’ve used, like strings and integers, it goes into a variable, in fact, it itself is just another data type.

01:27 - To make an array, first we need to tell it what type of data we want this array to be made up of, so, let’s just do a “string” for this example, so this will mean that the array will have strings inside it. And now, this of course is just a string, to make it an array of strings, we add some square brackets after the type. Not braces or rounded brackets, square brackets, they’re probably on the same key as the curly braces. Now, this is an array of strings, but, before we can use it, there’s one more thing we need to do – we need to “initialize” it. You see, as you might remember, because we haven’t set it to anything, this has gone to NULL.

02:11 - We can’t put anything inside the array when it’s null. What we must do is we have to set this to a new array, and when we make that array, we have to tell C# how big that array needs to be, so that means how many different items can we put inside this array. And when we do that, what will happen is C# will look for a spot in memory that can fit that many items in, that’s how it works. So, to do this, we take the array, and we set it to a new string array. And then, within these square brackets, we say how big we want it to be. So, let’s give it five items, why not.

02:54 - This means that it can have five items, five strings inside it. Awesome, we just made an array, now, it’s got nothing inside it, except five null items. So, let’s do some stuff with it. Let’s change the first item inside the array to something. So, here’s how we get stuff from the array and change stuff in the array, it’s very simple: We write the name of the array, and then we write square brackets, and within these we give it a number, and that number is which item we want to access, like the first item, or the second item etc. BUT there is one very important thing we must keep in mind, and I mentioned this when we did “for” loops. It starts at zero.

03:36 - To access the first item, we write “0”; To access the second item, we write “1”, to access the third, we write “2” etc. To set the first item, we just write an equal’s sign, and whatever we want to set it to, like “Hello”. If we wanted to look at what was in the first item, we would also just write the array name followed by the square brackets, and a “0”, so, for example, if I wanted to, I could print out what the first item is like this – this would print out what the first item is. Anyway, let’s get rid of that. OK, now, through the power of debugging, let’s look at the contents of this array, and see what’s inside it. Here we go, just put our mouse over it, and we can see it has five items, and the first one is, in fact, “Hello”, let’s set all five of them to something.

04:27 - So, because these start at zero and the length doesn’t start at zero, you’ll notice that to access the last item we have to write 4, instead of 5, and that’s an important thing to keep in mind. And, here we go, all five items have been set now. Alright, now, as we just observed earlier, if I don’t set one of them – they will go to “null”, right? If I leave one out, for example the third item, it will just on its own go straight to null when the array is initialized, however, that isn’t the case for all data types. So, this array here is made up of strings, it has strings in it, and they’ve all gone to null but it is important to know that some data types, and it’s generally only an odd few data types, physically cannot go to “null”. And two great examples of this are numbers and Booleans.

05:20 - So, if I make an array of integers, and I don’t set any of the items, all the items will go to 0, not null, numbers can’t be null. And if I make it an array of Booleans, then the items will go to false, not null. Technically, the reason this happens is because the numbers and Booleans are something called value types, whereas most other data types, like strings, that can be null, are “reference types”, but let’s not worry about that now, we’ll get onto that at a much later stage. It’s just a good idea to keep in mind, that not all data types can be null, and will go to something else when you don’t “initialize” them. So far, the two different data types we’ve learnt that can be null are strings, and arrays.

06:12 - Because, as we know, if we don’t write this “new” stuff here, if we don’t “make” this array, this variable will be null, so, strings and arrays can be null, while numbers and Booleans will go to 0 and false respectively. Now, we’ll come back to arrays, but this ties in very nicely with exceptions. You might be curious: What happens when you try to access a certain item, in a null array. Or, what happens if we have an array that has five items in it, and we try to access the sixth item, like this. Remember, that because these start from 0, this means access the sixth item.

06:47 - Well, these will all do something called “throwing an exception”, and, no it doesn’t involve anything getting thrown I’m not entirely sure where that came from. Now, let’s remember right the way back to Episode 6, where I talked about errors. I said that there are two different types of errors. A compiler, or “syntax” error is where there’s something physically wrong with your code, and the compiler can’t understand it – it can’t compile or turn this code into machine code, it physically cannot understand your code! And all syntax errors show up down here if I just write random text, that’s a syntax error, the compiler can’t turn this code into machine code the CPU can understand. That’s a syntax error, the other type I mentioned was a logic error, that’s where the code works, but it doesn’t quite do what it’s supposed to, in this case debugging will lead the way, if you’ve written a program and it doesn’t work – debug it! However, there is another type of error, now, these types of errors are very similar to logic errors, and it’s called a runtime error.

07:44 - And if you try to do something while the program’s running that you can’t, you’ll get one of these. So, like trying to access a null array or trying to access the sixth item in an array that is five items big. When you try to do these sorts of things, you will get a runtime error. The way runtime errors work in C# is C# provides an Exception system. And what happens is certain pieces of code can throw an Exception. For example, when I access an item on a null array, as soon as I try to access that item, an exception will get thrown. And we could also take advantage of exceptions, in our own code we can throw exceptions. Now, at the moment, that’s not very useful for us, and we’re not going to worry about that, but in the more advanced videos later on in the series I will cover how you can control the flow of exceptions, using something called a “try…catch” and various other things, but not in this video. So, what happens when we try to access a null array? Well, let’s find out. We’re not going to initialize this array, we’re not going to set it to something, so it will be null.

08:50 - Now, unfortunately, as I mentioned before there’s a failsafe built into the compiler that’s stopping us from using the array before we set it to something, so, it is null, but the compiler is trying to help us out here, but we don’t want its help, so we will specifically set it to null ourselves, to essentially say to the compiler “yes, I do want this to be null”. And then we’ll see what happens when we try to change all the items on it! Let’s run it. And, look at that! We just got our first runtime error, or exception. And it specifically tells us in the description of this exception, exactly what happened. And we got a NullReferenceException, and this is an exception that C# developers are very used to seeing, it’s practically become a meme, you’ll get this exact exception anytime you try to access something inside a null object, which C# developers often do because it’s so easy to accidentally leave some variable null, so, if you try to look an item inside a null array, that’s going to give you a NullReferenceException.

09:52 - Now, unfortunately for some reason I think there’s a bug in Visual Studio at the moment, but this yellow box here is supposed to be on this line, in order to tell you that the bug occurred on this line, so, not sure what’s happening there, I’ve never seen this bug before so I’m sure it’s new and it will be fixed soon, but, hey, that’s a logic error in Visual Studio, somewhere in Visual Studio’s tens of thousands of lines of code there is some issue that has caused that yellow box go one line too far down, as I said I’ve never seen that before, so I’m sure that will be fixed soon, this yellow box should be on this line here, to say that the exception happened on this line, because this was where we tried to access to access that item in our array. Also, if I try to access the sixth item in an array that’s only five items big, it will give me an “OutOfRangeException”, which is self-explanatory. Once again, the yellow box is one line too far down for some reason. So, you’ll get different types of exceptions for different things. Alright, so, I think we get how an array works, but now let’s look at using arrays alongside for loops.

10:56 - Now, one useful thing we can do with arrays is we can look at their length, and to do that, we just do the name of the array followed by a dot, and “length”. The dot means that we’re accessing the smaller stuff that the array of made up of, just like with “Console” followed by a dot, that’s us saying we want to access all of the smaller things that “Console” is made up of, we’ll get into what “Console” actually is a video in an upcoming video. Let’s make a simple program using loops and arrays together. Here’s what it will do: It will ask you to enter five names, you enter five names, and then it will print those names back out again. So, here’s how it will work: We make an array that has five items in it.

11:34 - Then, we’ll make a “for” loop that runs 5 times, so, to do that, we will make a variable “I”, and we will set it to 0, of course, then, we’ll put in our condition which is to run while I is less than 4, so, that means “I” will go 0, 1, 2, 3, 4, so the code will run 5 times. And, then, we make it so “I” goes up each time. Now, it’s important that “I” starts at 0, and not 1, because arrays start at 0. Then, inside this loop, we’re going to put in the correct items. So, the first time we ask the user for a name and take what they put and put it into the first item in there, the second time we’ll put what they put into the second item in there and so on.

12:13 - But how will we do that? How will we make it so that the first time the “for” loop runs, it puts the thing into the first slot, the second time the second slot and so on. Well, we can do it really easily. Let’s think about what “I” is each time. The first time run the “for” loop “I” is 0. In order to access the first slot, we need to put a “0” inside these square brackets. OK, fine, next time we run the “for” loop, so this is now the second time the “for” loops has run, what’s “I” now, oh, it’s “1”, exactly what we need to access the second item, and that continues for all 5 repetitions. Do you see it? All we have to do is just use “I” inside these square brackets, like this.

12:54 - And that is why we start “I” as “0”, because that way if we’re using it alongside an array like this, it’s really easy to put the correct values in the correct slots. If you still don’t get it, hopefully you’ll understand when we actually write the program and debug through it. So, let’s write this, of course I have a “ReadLine” at the end as usual to stop the program from just exiting. Now, let’s go, we’re going to make a string array with five items in it, so what we just learnt, we’re making a string array with five items in it. Now, just as a little bonus thing if you remember back to Episode 11 where I gave you the tips, let’s use “var” here, if you remember, “var” means C# automatically works out the type.

13:33 - So, based on the fact that we’re making a new string array, C# is able to work out that this variable is a string array, so that saves us writing it out twice, and that means if we wanted to make it an array of integers, we can just write “int” here and we don’t have to change it here and over here, it will just do that for us. Alright, the next step is to loop five times, just as I demonstrated a moment ago. And now we ask the user to input a name. OK, now this is the bit where we need to take what the user inputted and put it into the correct slot in the array, so, as I demonstrated, we will put it into the array at index and then substitute whatever I is in there. Great, now, the final part is to actually print out all of the items in the array, this time, we could just use less than 5, but, how about instead of doing this we look at the array’s length, so, how many items it has inside it, as I said, to do that, we take the array and hit dot, and you can see all of the smaller things the array is actually made up of, not the items inside the array, but what the actual array itself is made up of, and we want to look at the Length of the array. Cool, and in fact, why don’t we also do that up here in this “for” loop while we’re at it? So, now, if we wanted to change the program in the future to ask for 10 names, all we actually need to do is change this number, because if we make it 10, now the array can have 10 items in it, and now both of the for loops will go up to 10 because the array’s length has changed.

14:51 - Now, printing out what’s inside the array is super easy, and it will just take one line, so we won’t even need the curly braces, we will just WriteLine the current item here. So, now, this for loop will count up 0, 1, 2, 3 and 4, or however long the array is and every single time, print out what’s at that place in the array. Great! Let’s run this and see if it works. I’m just going to enter letters of the alphabet because I’m not creative and can’t come up with that many names, and watch! Look at that, after I entered five names, it said back to me all of the things I said… Now, let’s debug this to really drill down on what’s going on here. So, first we create the array, fine, now if we look at it, it’s just an array with 5 null strings. Then we start up a “for” loop again. So, watch what happens. We go into the “for” loop and “I” is 0.

15:42 - Then, we ask the user to input a name, and now, here’s what happens, we will change the item at position 0, (because that’s what “I” is set to) to whatever the user inputs, so, let’s do that and input something, and now look at that! The first item is now whatever we inputted, then we do that again, but now “I” is 1, so, we change the second item, and so on. And this is an extremely common pattern right here that you will find yourself using a lot, this “for” loop alongside arrays thing. And then at the end we do a very similar thing, and print out all of the items in the array. Great! We could take this further by asking the user how many items they want to input, like this, and then making the array that big. So, now, if I say five. It will make an array that is five items, big, if I say 10, it will make an array that’s 10 items big. As you can see here in the code.

16:42 - And, of course, since the “for” loops are using the length of the array as their ending they will automatically use whatever you inputted too. Well, that’s it, that’s all there is to arrays, seriously, arrays themselves are pretty simple really. However, we aren’t quite done just yet, because there are two more things I want to go over. The first thing I want to point is about strings, and, yes, just actual plain old strings, I want to introduce you to a new data type called “char”, which is short for character. A string is made up of characters. So, you could technically say that a string is a character array, and internally, so actually inside the string, yeah, that’s exactly what a string is, it’s just a fancy thing around an array – it’s really just a character array, an array of these “char” things here.

17:30 - Now, do you remember all the way back to episode 6 when I said use double quotes, do not use single quotes? Well, probably not, but I did say that, and that’s because when you use single quotes it will make a char, which is just one singular character. So, if I make a variable that’s got a character type, and I set it like this, then that’s perfectly fine. However, this is just one singular character. So that means I can’t put more than one thing inside these quotes, it won’t let me! This is just one character. So, double quotes make a string, single quotes make a single character, kind of makes sense when you think about it.

18:11 - Now, the reason this is important and relevant is because: Since a string is just a fancy array, we can access each character on it just like with a normal array. Watch this, here I have a string that just says “Hello”. And what I’m going to is make a character variable, and set it to the first item, or well, really let’s call it character, on the string, just like with an array! And, yep, that works. So, what is the first character on the string? Well, it’s a capital H, so this character here will be a capital H. Let’s write that out to confirm that, now, as I’ve said time and time again, WriteLine is smart, and will automatically convert the character into a string so that it can write it out to the console, because generally it wants a string, but don’t expect that elsewhere, if for whatever reason you need to convert a single character into a string, you can just look up how to do that, no big deal, you basically just put “new string” around the character.

19:10 - Anyway, if we run it – indeed, it got the first character. Now, of course, just with an array, be careful with this, if you try to access the sixth character, you will get an “OutOfRangeException”, because you’re trying to access a character that’s higher than the string’s length. And, of course, because a string is just an array, you can actually write the string followed by a dot and the length, you can find out how long a string is just like that, that might even be one of the tasks, of course with a twist, it’s not going to be that easy. Alright, we’ll get back to working with strings like they’re arrays in a bit. But, now, let’s answer the first question you probably asked yourself near the start of the video.

19:45 - “What if I want array that can grow and shrink, so like if I don’t know in advance how many items there are going to be in the array, how can I deal with that?” Well, there’s an extremely handy thing called a “List” for exactly this, it’s an array that doesn’t have to be an exact size. Let’s first look at how to make a list, so, first, make sure you have “using System.Collections.Generic” written up here, if you don’t, just add that up here. Now, to make a list, we first write “List”, and this is where things get interesting, now we won’t have to understand what this actually means until we get to generics, which is a quite an advanced topic we’ll get to way later in the series, so just copy this out. Then, we do angle brackets, which are typically above the comma and dot keys, like this and within these angle brackets we put what type of array we want, so, want items go inside it, let’s have an array of strings, which now know is basically just an array with an array in it, because strings are like fancy arrays, which, yes, you can absolutely have arrays inside arrays with two square brackets.

20:49 - And now, just like with an array, we have to initialize it, it can’t be null, so we write “new”, and we have to give the entire type as it’s written over here. And then on top of that we put in some regular brackets at the end and a semicolon. Now, notice how we didn’t have to put a number inside these brackets? That’s because this list doesn’t have a fixed size, it can change! Let’s just use var here, because otherwise we’re repeating a lot of stuff. Now, let’s talk about how to use a list, because it is a little bit different from an array, but not too different. So, as it is, after you’ve initialized it, it has 0 items in it.

21:24 - I’ll cover a few things we can do this to a list, but there are hundreds more, and I recommend you actually take a little look for yourself, you won’t understand what all of them do, maybe not even most of them, but some of them should be pretty clear, in the description I’ve got a link to a list of all of the things you can do a list, there’s a lot of useful stuff in there. Anyway, the three big things you can do to a list is “Add”, “RemoveAt” and “Clear”. They’re simple, so, our list has nothing in it right now, and what we do is we run “Add”, and just put whatever we want to add in the brackets, and as it says on that page I linked you to, it will add an item to the end of the list, so, an item will appear there. Also, I have the numbers over on the left to help make everything clear. So, we could put the “Add” inside a “for” loop and have lots of things added to the list. There you go, now we have “4” items.

22:16 - The next one we can use is “RemoveAt” and we just give this one a number in the brackets, and that’s what the index we want to remove at, so, if I put a 1 in the brackets of it like this, then it will remove the item at index 1. Now, one thing that is important and that can trip you up, if you’re using “RemoveAt” in a “for” loop, all you’ve removed it, you’ll notice that the indexes after that item will change, you’ll have to make sure you are aware of that, and make sure “I” changes accordingly. And, the final one is simple, it’s called “Clear” and it will just get rid of everything inside the list. There’s also one more thing important thing I can to mention, in a list if you want to get how many items are in it, you need to use “Count” instead of “Length”, in fact, there isn’t a “Length”, so you do the list followed by a dot and “Count” to get how many items are in it, instead of “Length”. Now, if we want to look at or change an item that we’ve already added to the “List”, we can do that exactly like with an array.

23:14 - We just say the variable name, followed by square brackets and which item we want to access, just make sure though that you have that item in the list, otherwise, you’ll get an “OutOfRangeException”, of course. Alright, we’re about to do a task, just one thing I want to point out that I don’t think I’ve pointed out before, if you have a “for” loop within a “for” loop, then you usually call the second one’s counter variable “j”. So, you have “I” and then “j”, that’s just something that you commonly do when naming these, of course you could name these whatever you want, but generally it’s pretty simple to name them like this. Also, there are some other things like two-dimensional arrays, which are arrays that have an x and y thing on it, but those are a bit of pain, so I won’t cover them in this video. So, we’re going to make a shopping list program together, let’s look at what’s it’s going to do.

24:02 - So, here’s what will happen, it will show us a list of all of the things in the array, there aren’t any right now, so it’s not going to show anything. Then, this is like the main menu, here we can choose to either add something to the array to remove something from the array. If I choose add, I can add an items, I won’t enter things in, I’ll just type something random. And, now, it will show us all the items in our list, and we can choose to add or remove again. So, if I say “Add”, then it will let me add another item, like that.

24:33 - Then, if I want to remove an item, it asks me which one I want to remove, but this is important. This isn’t a zero-based, this doesn’t start at zero, this starts at 1. 1 is the first item, because that’s nicer for the user, so, in our code, we’re going to have to take what they input and minus 1 from it, because of course arrays start at 0, not 1. We also want to stop them from entering invalid numbers, so, we’ll do that too! Alright, let’s go write this out. So, we’re going to need a list for this one, because we need to be able to add and remove items, we don’t know how big it will be in advance.

25:10 - Next, we’re going to setup a loop, now, as it is, the program will never exit until you press the close button, but you can add an exit option, if you want. Now, this is quite a big task, so what we need to do is really think here about what we want, and do each section, then put it all together. So, first, let’s make the menu things, the thing that asks me if I want to add or remove items. So, here we go, I just added some “WriteLine”s that will tell the user that they type “add” and “remove”, so, now we’re going to take what they chose and put into a string variable. Then, if they said “add”, just temporarily, before we put in the actual add code, let’s just dump a WriteLine in there, saying that they chose “add”.

25:51 - Then, I’ll do the same for “remove”, making that “else if”, and if they didn’t pick either of those, we’ll say that what we those was an invalid option. Alright, now, let’s not forget, we want to ignore the capital letters, so we’ll convert this string to lower case, and then make sure in the “if” statements, these are lower case. So, now it doesn’t matter if they write these with capital letters, it will always work. Great! Let’s test out this very first part of the program. If I say “add”, it says I chose to add an item, and if I type “remove”, it says I chose to remove an item, and, if we don’t enter anything valid, it just tells that it was invalid.

26:26 - Awesome! That’s that bit of the program, now let’s fill in the gaps. So, if we chose to add an item to the shopping list, we’ll just ask the user what they want to add, and take that and put add that to the end of the list, just like this, we take what “ReadLine” gives us, and put it into the “Add” on the list. Alright, now, let’s look at the removing. Now, removing will be a little bit trickier, because as I said earlier, we want to check if the numbers they entered is valid. We don’t want our program to throw an exception, you never want your program to throw an exception. So, we’ll ask them which item they want to remove.

26:59 - And, then, we get them to input it, remember, using “Int.Parse”, this all basic stuff we learnt before. Now, as I said earlier, they will be entered “1” to access the first item, and “2” to enter the second item, and that’s just going to get in the way, so, instantly right here, after we’ve converted it into an integer, we’re going to minus 1 from it, so now it’s correct. OK, now, we need to check what they’ve entered using some selection to avoid an “OutOfRangeException”, and if they entered a number that’s too big or too small, then we’ll tell that what they entered was incorrect. The first thing we want to check for is if they entered a number below 0, so, we’ll say “if” the choice was less than 0.

27:37 - OK, now, there’s also one other thing we want to check for, and that’s if the choice they entered was bigger than the length, so, we’ll say or the choice they entered was bigger than the length. And then, if so, we will say to the user that they didn’t enter a valid number, and then, what we want to this do is we want it to go all the back up here again, so, if they enter an invalid number, we just go back up to the top of the loop and start from the beginning again, and we can do that with “continue”, don’t use “break”, that will just make us jump out of the loop and end the program, but “continue” will make us go back up to the top of the “while (true)” loop, so if they enter something invalid, nothing happens. Now, there are two things I want to comment on here. Firstly, you may have noticed I used an OR here, a Boolean OR operator, and it’s important that we used an OR, and not AND. Because we’re check if it’s less than 0 or if it’s bigger than the count, so, if it’s either one of these, it will run and then tell the user that it’s not valid and all of that.

28:40 - Whereas, if we used an AND here, then that would mean that it must be both below 0 and above the count of the list, which, technically, it physically can’t be. It physically can’t be less than 0 and bigger than the list, so that’s why we need to use OR here. And, also, there is a slight bug with this right here. Let’s look at this list here, with five items. Now, what would happen if the number was five, even after minus 1, was “5”? Because, that’s obviously not a valid option as we can see here, so it should say that it’s an invalid option, right? But, unfortunately, our code won’t detect this as invalid, because we’re checking if their choice was greater than the count, and it isn’t.

29:20 - 5 is not greater than the length, but as we can clearly see here, it’s not a valid choice, so, we need to if it’s greater than or equal to, like this, now this will check it correctly. If choice was “5”, it wouldn’t let it through which is correct. So, now, provided they haven’t been stopped by this if statement here. We know that they’ve entered a valid number, so we’ll just put that number into “RemoveAt”, and there you go! That’s done. Now, there’s just one final thing we’re missing. We need to show the user what they have in the list every time it asks them whether they want to ‘add’ or ‘remove’. So, we’ll say “These are the items in your list”, and then, we need to say all the items in it our list. So, to do that, we’ll make a “for” loop that will go through everything inside the list and print it out. And, just to make it even nicer, we’ll also make it say which item is what number… We must make sure we add “1” to I when we do that though to make it look like to the user it’s counting up from “1”. And, we’re done! There’s just one minor improvement I want to make here.

30:25 - If the list is empty, how about we make it say, “You have nothing on your shopping list”? That would be nicer. So, if the count of the list is 0, so, if the list has nothing in it, we will say that our list is empty… Otherwise if it isn’t empty, we’ll show all the items in it! Whew! That was a quite a long task there, but there it is, in all its glory! So, as usual, hop on over to the tasks page, I have some tasks there for you to do, so please go ahead and do those, they’re good practise to get yourself breaking these things down into the smaller parts on your own! Don’t expect miracles, it’s OK to take a long time on these tasks, especially these tasks, look at how long it took me to explain this one, just keep going at it! What might be good for you if you go to this task we just did, copy and paste its code into Visual Studio and debug it so that you can make sure you absolutely understand what’s going on. And feel free to rewatch any videos if you can’t quite remember a topic that well. Alright, I’ll you all next time, where we’re going to cover methods! Bye! .