C# Arrays - Lessons

 

Introduction to Arrays

In the beginning we’ll lay the foundation for understanding arrays and then we’ll jump into a bit of code and start with the basics of how to declare and array, how to fill it and how to pull information from the array.

Stepping Through an Array Using a Loop

Let’s get some practice stepping through an array. How do we do that? Typically, we use loops to do that. Using a Lottery Number Generator application we are going to do just that. It’s a simple program. The program uses a random number generator to generate five integers. Rather than place them on the screen immediately, it places them in a array. We don’t do it here but by putting them in an array we would have a chance to check for duplicates before placing them on display. But we’re going to keep this simple and just place the random numbers in an array. Next, we’ll read the array and place the contents of each element in a label on the form.

Working with Files and Arrays

Way back when we learned how to read and write a file. The key element to doing that was the loop. And last time we learned how to step through an array. Again, the key element to doing that was the loop. This next piece ought to be a piece of cake. We are going to use a loop to read and write a file as well as read and write an array.

Bullet-Proofing Files and Arrays

What I want to do now is break the program we did in the last video. Once we’ve seen how it can be broken, we will put in the pieces to protect it from breaking.

There are two things to consider here. We are working with a file so things can go wrong with the file. File not found. File corrupted. File in use. Those are just a few of the things that could happen when you are working with a file.

The second thing to consider is the array itself. It is set up to be a certain size. We can’t put more items into it than what we have allotted. Also, when you use a pointer to travel through the array, that pointer needs to be a positive number, greater than or equal to zero and it can’t be larger than the size of the array less one. In other words, for an array of 100 elements any pointer needs to be 0 or greater without going above 99.

This video will show you how to set all this up.

Passing Arrays as Arguments to Methods

It is a good idea to strive to keep the global area clear. And that means we pass variables and arrays to methods. That’s what this video is all about.

You’ll note in this video that the only way to pass an array to a method is by reference. And since it is the only way, you don’t need to include the word REF. You just need to name the array. For consistency it might have been a good idea to include the REF but the powers that be didn’t do that.

The Sequential Search

Sequential searches are not efficient. You certainly don’t want to use one if you are searching through thousands of records. There’s plenty of other options for that. But for searching through small files, they are extremely easy to implement. And with the speed of today’s machines, you have your answer in microseconds.

Well, what is it? It’s nothing more than taking a value and matching that value with the value contained in each element of an array, one at a time. Stepping through an array is a common technique and it is used a lot. It’s easy to master and you’ll find there’s a lot you can do with this simple technique.

Array Total and Average

So many applications require the totaling of numbers. Often these are in arrays. Often they are also in files but they get moved to arrays so we can perform many different operations on them. Two of those operations are generating a total and obtaining an average.

Ideally, we would read these numbers into an array. The array could be the same size as the number of records but generally it’s not. So, we end up reading these numbers into an array so we can work with them. As we read these numbers, we get the number of records simply by counting them as they are read. Knowing how many there are gives us a stopping point when we total the array. It also gives us the divisor we need if we want to calculate an average.

Array High/Low Values

This one is simple. Finding the highest value in an array and finding the lowest value in an array are almost identical.

What you are basically doing is setting up a single variable to be the highest value. Then you place the value of the first element in the array into that variable. Initially this is considered the high value. Next, using a loop, you move your pointer to the next element in the array. If the value is higher, you replace the contents of the high variable with the new value. If it is not larger you just skip it.

The loop continues and you make the comparison with each element in the array. When you are all done the value in the variable is the true highest value in the array.

Finding the lowest value works the same way except you are looking for a value lower than the one in the comparison variable.

Sorting an Array

To sort records, we establish a pointer at the first element in the array. Element 0. And our pointer will be an integer variable named X.

We also establish a second pointer called Y. It initially points to the first element following the X pointer. Initially this would be element 1.

Starting at these two positions the Y element is compared to the X element. If the Y element is less than the X element the two values are swapped. If the Y element is not less than the X element, we increase the Y pointer to the next element and perform the X and Y comparison again. If no value is found less than element 0 after the Y’s first pass through the array we increment X by one and set Y up at the first element following X. For the second pass X would be pointing at element 1 and Y would be pointing at element 2. The process continues.

Now, when a swap is required the value of the X element is placed in a temporary holding area, a temporary variable. The Y element is placed in the X element. Once that’s done the value in the temp variable is placed in the Y element. And Y continues through the rest of the array.

Long story short, X travels through the array once. Y travels through the once for every time X moves. The distance, however, is decreased by one for every pass it makes. When complete the array is in alphabetical order or numeric order depending on the data type in the array.

Seeing it played out behind me helps. But setting up this process requires looking at this via flowchart and even via pseudo-code.

The following video will go through all this and show you how to set this up in your program.

The Binary Search Algorithm - Part 1

When you have thousands of records in a file one of the quickest ways to search for a single item in the file is by doing a Binary Search. Binary Searches are extremely efficient. But to be efficient, they need to follow a set of rules.

The first rule is to have a key element in the record to search on. For example, in a customer file you may want to search on last name, or phone number, customer number. All the other information in the customer record will be available to you when you find that name, phone number or customer number.

The second rule is that the file needs to be sorted.

Rule three has us split the file in half. We determine which half our record is in and then keep splitting what’s left until we have our match --- or determine there is no match.

The following video is part 1 of the Binary Search process that will allow us to search through a set of movies to determine what year the movie was released.

The Binary Search Algorithm - Part 2

Welcome to part 2 of the Binary Search lesson. Last time we prepared the form, coded the non-essential buttons, established the array, and placed the method calls in form_load.

Part two is all about preparing the data.

You might recall that the data we are searching comes from spreadsheet data that was saved as a tab delimited text file. That text file is what we are going to read into our application.

This next video will step you through the process of reading such a file and extracting the year and movie name so they can be loaded into two arrays. It will be followed by the code needed to place the movie array in alphabetical order and keep the proper years in alignment with the sorted movie names.

The Binary Search Algorithm - Part 3

Welcome to part 3 of the Binary Search lesson. This is the final piece. It’s all about the search.

Our data is in place in two arrays. The key file, the movie name array, has been sorted in alphabetical order. The years in the other array have been sorted based on the movie names. So, any index encountered in the movie array will point to the proper year in the year array.

One word of caution. If you are working on a project similar to this, you’ll realize that coding this is not trivial. The likelihood of having coding issues is pretty great. Determining what those issues are and fixing them is a normal part of the process of coding.

In this following video the project is successfully coded. But not without a few issues. Resolving those issues are a part of this next video.

Two Dimensional Arrays

Two dimensional arrays are nothing more than spreadsheets. Yup, the one-dimensional array is either a row or a column, the two-dimensional array is both rows and columns. They are just as easy to use as a one-dimensional array. Initially, however, they can be a little confusing because it takes a set of nested loops to access all the content.

Over twenty years ago I was still consulting but I was also teaching. I was teaching a course in advanced visual basic – talk about programming in any language! One of the things I had my students do was set up the game “Wheel of Fortune”. Anyone familiar with the game will recognize that the puzzle to solve was a series of letters in four rows. Essentially, this was an array.

Rather than me explaining it I can show you this old program from over twenty years ago.

Multi-Dimensional Arrays

If you can have two dimensional arrays, why not three, four or even thirty-two. Yes, you can have a 32-dimensional array in C#. Why you need to go that deep, I couldn’t say. But when I was first learning arrays, I was hard pressed to understand why I would need three!

Didn’t take long to see the light. Multi-dimensional arrays are very important in the gaming world. But they are important in the business world as well.

This video will show you how to set up a two-, three- and four-dimensional array. But it will do more than that. It will show you a sound example as to why you might need a three- and four-dimensional array. And later this will get supported by creating a two-dimensional array app that will then be converted to a three-dimensional array app and finally a four-dimensional array app like the one appearing on the screen now.

Multi-dimensional array apps can be confusing if you charge ahead and just try to put one together. The multi-dimensional arrays cause a certain degree of complexity because of the need of nested loops going three and even four or more levels deeps. But once you understand how a 4D array is used this all makes sense.

Jagged Arrays

Welcome to jagged arrays. You’ll find they are a bit obscure. In fact, if you research programming textbooks, you’ll find that some books give this topic a page or two while others dismiss the concept entirely.

If you research this topic on the internet, you’ll find a repeat of the same examples from a variety of authors. Truth is, almost no one gives us a practical example of why you might want to use a jagged array. In fact, if any of you out there have a practical example I’d love to see it.

Not this video, but in the one following this video I did put together a practical example as to how you might use a jagged array. But, even in my example I would rather opt for a 2D array.

But that’s okay. Between this video and the next I think I’ve put together the clearest explanation of how jagged arrays work. This first video will use the classic example found all over the internet and in most books. The second video will use strings and create an application that actually could be used in the real world.

Jagged Array Practical Example

Time for a practical example. Is there such a thing?

Well, a little research suggests that jagged arrays are useful when dealing with large datasets. Supposedly they can store data in a more efficient manner. And, yes, when you see that every cell in the jagged array has data – no blanks – and that each row in the jagged array has a defined length, no time is wasted looking at empty cells. But since computers operate at the speed of light, it takes a lot of data to actually appreciate this advantage.

The main disadvantage to the jagged array is their degree of complexity. Every row in the array can be a different size. A good understanding of the many ways to traverse an array is important when using the jagged array in an application.

Many books say very little about Jagged arrays. Some say nothing.

I’ve been consulting and teaching for many decades. I’ve never come across a problem that needed to be solved using a jagged array. I’ve always had the memory I needed and the computer speed I needed to solve applications using single and multi-dimensional arrays.

That said, it is important to know what these things look like and how they might be used in an application.

To show you a possible use for jagged arrays I looked at the food industry. We have all these foods on store shelves and all these foods have ingredients. There is no specific number of ingredients in the foods we purchase. A jagged array of all the foods in a grocery store would be thousands of products all with a variable list of ingredients.

To simplify this application, I chose to simply create a jagged array for four products. It would be simple to increase this number. But four products will give you a good example of how such an application could be built.

The List Collection

Let’s take a look at the List.

The List collection is very similar to the ListBox. The main difference is that you don’t have the box. Essentially the list is a single dimensional array that can grow and shrink as needed. The beauty of this is, when you read a file, you don’t need to know how many records you are going to read. You simply keep adding the items, as you read them, to the list.

You saw something similar to this if you watched videos in the Speed Track section. There we built a database-like application using the ListBox to store data. I put together a similar application for this lesson. However, instead of using a ListBox, I used a List. And since all the data is in memory and invisible to the user, I used a label to display one element in the List and provided the user with a set of navigation buttons so the user can step through the list. This is a very common function when working with database applications.

This video is an intro. It sets the stage for the List. In future videos I’ll show you how to build the List application, step by step.