3 C
New York
Friday, February 7, 2025

Support US

spot_img

Learn C# Week 4 – Arrays

Welcome to the fourth programming lesson in C#. Unfourtanely for those following along the move to the new domain name, TICGamesNetwork, has caused previous work and articles to be left behind. The content should come back someday but for now it seems as though we will have continue without it. As an added measure to ensure this content isn’t lost from now on I will be posting these articles and code samples on GitHub. If you don’t know what GitHub is the provided linked article should give a simple explanation. You don’t need to learn how to use GitHub, that is just for my own sake but if you know how to use it feel free to follow it.

Now if I remember correctly the last lesson assigned a homework in which readers were supposed to creat a simple calculator. Using loops and if statements you were to have a user enter some values and the calculator would display the results. It would keep the user in the program with a while loop and eject the user out of the loop if they choose to exit the program. Below is a screen shot of the solution and here is a link to the GitHub page hosting the code just in case you want to copy and past it to Visual Studio and see if it works. Remember to understand what is happening in the code. That’s the most important part.

Learn C# HW Week 3

Week 4 Arrays

C# Arrays

Arrays are what we call in computer science a data structure. It’s a way in which we can store data in a list for later use. To explain it as simple as possible when you’re using an array just think of an array as having a block of memory, divide that block into several pieces and inside each piece you have the ability to store data in it. Each block has an address and you store data in each location and move to the next spot by adding one. As stated in the beginning of these lessons, computers are dumb we can’t just tell it to fetch data from anywhere, we need to add the functionality. Well at least in other languages like in C++ you had to, in C# the creators of the language made life a little bit easier for you. In C# Arrays are treated as Objects, we won’t be getting in depth into object orientated programming (at least not at this stage) but know that the difference between the two is that in C or C++ an Array would be like a foundation to a home, basically the bare minimum while in C# as an Object it’s like the home itself with access to different rooms that each do their own duty.

The full code snippet of what is going on this week is live on Github, check it out and read the following if you want an in depth look at what’s happening in the code. Create you project in Visual Studio, write it out on your own and read what’s happening. Experiment and make your own changes. When your done try doing the HW at the bottom.

Creating Arrays

A regular variable is created like this.
int number;

An array is created in the following manor.
int[] number;

Notice that we define the data type of the array just like a regular variable right at the beginning. We put brackets right after that to signify an array is being created. Lastly we name the array. Notice that both the variable and the list have no values initialized. Each is blank with values we don’t know somewhere in memory. Recall that a variable is just a place in memory that you gave a name to. The same is true for arrays.

//Create an array and specify how many spots your array has.
int[] numbers = new int[4];

The above code snippet creates an array called numbers that will hold values of type int. Next we created the array with the size of 4. This means that the array in memory starts at a certain location and the next three spots are reserved for the array. Basically the 4 inside the bracket is the size of the array.

Assigning Values to Our Arrays

This does not mean that the value of our array is 4. It just means we are keeping track of a list with 4 open spots. In fact if you try and print what’s inside that array you’ll just get four zero’s. In order to assign a value to this list like we do with variables we have to do the following.

//Filling our array of size 4 with the values 4, 5, 6
numbers = new int[] {4, 5, 6};

If we print the above the values that will be displayed are 4, 5, 6 and 0. The array is of size 4 and because we only gave it 4 values the last spot still has a zero in it. Adding values at a later time instead of immediately in an array could be used for when we want to keep track of items a user gains in a game. For example in a Pokemon game we could create an array and add Pokemon to a list each time they get a new Pokemon.

//Alternatively you can create an arrays and initialize them immediately
int[] numbers = new int[] {4, 5, 6};

This is if you already know what your array will have in it. This could be a way we implement lists in a video game like items at a shopping mart. We already know what items we want to be in the game and would just call that array when we want to display the items for the user.

Traversing Arrays

So now you know how to create and assign values to arrays but how do we list them? This is the tricky part. In most languages Arrays are a powerful tool to have under your belt but in certain programming languages like C++. An Array could be one of the most dangerous aspects in programming. Accessing certain elements in arrays, lists and other programming data structures is a risk. Like I stated earlier we are dealing with a list of memory locations each located next to each other. In order to access values in our arrays we start from the beginning and move to the next spot until we reach the end. Humans aren’t perfect and computers along with Visual Studio don’t tell you specifically when you make errors when it comes to traversing arrays. Most computer science professors usually refer to such issues as shooting yourself on the foot. A Lot of malicious software involves arrays going outside of their range into memory it shouldn’t go to causing major problems. The blue screen of death comes from such behavior.

C# improves on many older languages and gives you a safe way to display every item in an array.

Using the foreach loop a lot of the dangers are taken care of. Check out the example below.

 

foreach(int i in numbers){

Console.WriteLine(“{0} “, i);

}

If you’re using strings replace int i with string i.

The foreach loop above creates an integer i that will be used as a variable to hold all the values. Because the variable i was created inside a loop it will only exist inside the branch of code. If you try to use it out side of that loop it won’t work, you’ll need to make a new variable for i.

Inside the loop itself we have a write line that will start from the first position zero, all the way to the final spot in the array. It’s a little abstract at this point but if you look at it from how other languages handle arrays it may become more clear what going on in the background.

Try writing a Console.Write with just the i inside. You’ll notice that the formatting will be gone. The “{0} ” is used to format how we want the array to display, notice the space is visible if we use Console.Write(“{0} “, i);

In a language like C++ traversing an array is more dangerous but you get to see more clearly what’s going on. You can use this option in C# as well but as stated before, it’s more convenient and safer to try the first way of traversing arrays.

for(int i = 0; i < numbers.Length; i++){

Console.WriteLine(numbers[i]);

}

In this for loop an integer i is created that starts at 0. It will then never come back to the creation of that variable, it will just check the next two arguments. First it will check if i is less than numbers.Length which is a built in functionality of arrays in C#. numbers.Length gives you the size of the array, were this any other language you would have to program that functionality yourself. That being said returning back to the second argument of the for loop, the loop will check whether the i is less than the size of the array, because are variable is 0 and our array is greater than that it will do what’s inside the loop which is writing numbers[i]. numbers[i] is the location in memory that each item is at. So by that logic.

int[] numbers = new int[] {4, 5, 6};

numbers[0] would display 4

numbers[1] would display 5

numbers[2] would display 6

After the inside of the for loop prints out just 4 it will go back to the top go to the third argument which is i++. That increments the value of i by one so it is now 1. It then check the second argument again, see’s that it is still below the size of the array and does what is inside the array, because i is now 1 it will display 5. It then does that loop again incrementing i by one and displaying 6. When it returns to check the second argument again it will be incremented to 3 and will notice it is no longer less than the size of the array and exit the loop. This successfully prints out all of our values. A common problem among computer scientists is the classic “off by one” not everyone starts off at 0, some start at 1. If you start by 1 you won’t be able to print all of the values.

Homework

Well now that you know how to create array and traverse them how about trying it out on you own? Below is a screen shot of a program, try implementing a similar program using arrays.

The link to the solution will be posted here after a week. Feel free to discuss or look up how to solve this problem. You’ll need to create a variable that will need to hold the selection the user enters in my case “Revive.” You will need to create an array and display them. You will then need to compare the users selection with an if statement to the values in the array. Hint, you’ll need to do the comparison inside a for or foreach loop.

 

HW Solution for Week 4

Related Articles

Stay Connected

20,921FansLike
3,600FollowersFollow
5,573SubscribersSubscribe
- Advertisement -spot_img

Latest Articles