Working with Arrays

Arrays are a powerful feature in every programming language but even more useful in C#. This is because arrays are a type of object in C#. Like other objects, arrays have methods and properties. When you understand some of these characteristics of the array class, you can do many interesting things with arrays.

Using the Array Demo Program to Explore Arrays

The Array Demo program featured in Figure 8.5 puts the array class through its paces, showing off some interesting capabilities. The program features a list box control for displaying the array (lstOutput), a pair of option buttons (optSorted and optUnsorted) for determining whether the array is sorted, and a button (btnForEach) for demonstrating the foreach loop. Notice that the search button (btnSearch) and its associated text box (txtSearch) are disabled. The user can see them, but they are not currently functional. This is because the searching operation I’ll be demonstrating works only with sorted arrays. When the array is sorted, I’ll make these controls available to the user.

Figure 8.5. An array of programming language names is displayed in a list box. The array is not in any particular order.


Building the Languages Array

The Array Demo program is (not surprisingly) closely related to an array. For lack of anything more interesting, I chose to create an array of programming language names. Because I use the array throughout the program, it is declared at the class level:

string[] languages = {
  "Java",
  "Basic",
  "Pascal",
  "C#",
  "Perl",
};

string[] sortedLangs = new string[5];
showUnsorted();

If you examine the code, you will see that I created the array a little differently than in the Counter program. If you know exactly what elements are going to go in the array when you create it, you can “preload” the array, as I did in this example. Notice the use of braces to indicate the beginning and end of the array definition. Also, because arrays can be large, I chose to put each element on a different line of the code listing.

The sortedLangs variable is another string array of five elements. This array will hold the sorted version of the languages array.

The last line calls a method that will show the unsorted version of the array in the list box. The details of that method are explained in the next section.

Sorting the Array

When you have an array of data, you usually need to sort it. Sorting an array by hand can be difficult. Computer science instructors love to drone on endlessly about the subject. In C#, however, you usually don’t have to worry about the details of sorting because the array class already has an efficient sort method built in. Figure 8.6 shows the array after it has been sorted.

Figure 8.6. When the user chooses the sort option, the array appears in alphabetical order.


The array is invisible to the user. Arrays are data structures stored in the computer’s memory. For the sake of demonstration, I’ve copied the array over to the list box so that you can see what’s going on “under the hood.”

The user can choose the sorted or unsorted view of the array via the option buttons. Option buttons, as you recall, are handy when only one out of a group of choices should be selected at a time. I added code to the default event of the option buttons to manage the array sorting.

Creating the ShowUnsorted() Method

Because the unsorted array needs to be displayed at the beginning of the program and whenever the unsorted option is selected, I decided to make it a method:

private void showUnsorted(){
  //displays the array in the list box in its default state
  1stOutput.Items.Clear();
  1stOutput.Items.AddRange(languages);
} //end showUnsorted

The ShowUnsorted() method begins by clearing the list box. You might expect the list box class to have a Clear() method (I expected that, anyway). It doesn’t, exactly. Instead, the Clear() method belongs to the Items property, which is an instance of the Listbox.ObjectCollection class. Although this seems complex, it’s actually a good thing because the ObjectCollection class is a handy class with neat features for adding elements to a list box, clearing the elements from the list box, and more. Figure 8.7 shows the help screen for this class.

Figure 8.7. The methods of the Array object make it easy to work with, especially if you are working with some kind of array.


Specifically, the Clear() method is used to clear all elements from the list box, and the AddRange() method is used to copy an entire array to the list box. If you want to add only one element at a time, use the Add() method instead. As you can see, the list box control is like a visual wrapper around an array. It’s easy to copy array values to the list box and get an array from the list.

Handling the Unsorted Option

When the user clicks the unsorted option, the optUnsorted_CheckChanged() method is automatically called. The code for this method is very straightforward:

private void optUnsorted_CheckedChanged(object sender, System.EventArgs e) {
    btnSearch.Enabled = false;
    txtSearch.Enabled = false;
    showUnsorted();
} // end optUSorted

If the array is unsorted, the search method will not work, so I disabled the searching controls. Doing this is a good idea because it prevents the user from getting an error. When the searching controls are turned off, the method calls the showUnsorted() method, which copies the original (unsorted) languages array to the list box.

Handling the Sort Option

If the user chooses to sort the array, an event handler of the optSorted object does the job:

private void optSorted_CheckedChanged(object sender, System.EventArgs e) {
  languages.CopyTo(sortedLangs,0);
  Array.Sort(sortedLangs);
  1stOutput.Items.Clear();
  1stOutput.Items.AddRange(sortedLangs);
  btnSearch.Enabled = true;
  txtSearch.Enabled = true;
} // end optSorted

Because the user might want the original array again, I decided to sort a copy of the original. The languages variable is an array, and the array class has a CopyTo() method. This method takes two parameters. First, it needs the name of an array to copy to. Also, it needs to know which element to start with. The target array should have the same type as the original and should have at least as many elements as the source array. In this case, I called the sorted array sortedLangs. The Array.Sort() method provides an easy way to sort the array alphabetically. After the array was sorted, I cleared out the list box and copied the sortedLangs array to it.

The user should be allowed to search the array now because it is sorted, so I enabled the button and text box for searching.

If it bugs you to have elements on the screen that are visible but not available to the user, you can make them completely visible and invisible by manipulating the Visible property instead of the Enabled property. Some argue that leaving controls visible but disabled gives the user a clue that searching the array is possible, but not in the program’s current state.

Searching for an Element

If an array is large, searching through it to find where a particular element is in the array can be very helpful. Although the arrays used in this demo are not large enough to need this functionality, it is still useful, especially because the Array object has a very nice search method built in, as illustrated in Figure 8.8.

Figure 8.8. The user can search for an element to see where it is in the array.


Searching efficiently for elements in an array can be surprisingly difficult, especially if the array contains hundreds or thousands of elements. One of the most powerful types of search algorithms is the binary search. It works only on sorted arrays but can quickly find where a value is in even very large arrays. This binary algorithm is the one implemented in the BinarySearch() method. Searching for a value in the Array Demo program might seem trivial because the underlying array has only five elements. Searching and sorting arrays are much more critical operations when the array is larger, but these operations work identically on smaller arrays, too.

The search operation happens when the user clicks the Search button:

private void btnSearch_Click(object sender,
  System.EventArgs e) {
  int theIndex;
  string message;
  theIndex = Array.BinarySearch(sortedLangs,
    0,sortedLangs.Length, txtSearch.Text);
  if (theIndex < 0){
    message = "not found.";
  } else {
    message = sortedLangs[theIndex];
    message += " is at position "; 
    message += theIndex.ToString();
  } // end if
  MessageBox.Show(message);
} // end btnSearch

The method has two variables. theIndex stores the results of the search, and message holds a message to the user regarding the success or failure of the search.

I used the BinarySearch method of the Array class to search for the contents of the txtSearch text box in the sortedLangs array. The BinarySearch method also requires a starting number and length. I specified that the search should start at element 0 and continue for the length of the array. If the search value is not found, the algorithm returns a negative value, so I tested for the not found condition. If the result of the search is negative, I inform the user that the search was not successful. If the result is positive, the program returns the location of the value in the array.

Note that the elements are counted beginning with 0. Even though Basic is the first item in the sorted array (at least, to human reasoning), it is reported as element number 0.

Using Foreach with Arrays

You learned how to use the foreach loop in Chapter 3, “Loops and Strings: The Pig Latin Program.” However, my explanation of the loop in that chapter is weak because the foreach loop is closely related to arrays, which you hadn’t learned yet. Figure 8.9 illustrates part of what happens when the user clicks the forEach button.

Figure 8.9. When the user clicks the forEach button, the elements of the array are shown one at a time.


Wanting to step through the elements of an array one at a time is common. Arrays and for loops are a natural combination because doing something to each element of an array one at a time is so common. Although you can use a for loop for this purpose, the foreach loop makes examining an array, element by element, even easier to do.

private void btnForEach_Click(object sender,
  System.EventArgs e) {
  //demonstrates the foreach loop used with arrays
  foreach (string theLang in languages){
    MessageBox.Show(theLang);
  } // end foreach
} // end btnFor

The foreach loop is a special variant of the for loop. It requires a local variable of the same type as the array and the array name. In this case, theLang is a string that holds each value in the array. Because it’s a string array, theLang must be a string value. The variable name must be followed by the keyword in, followed by the name of the array. The loop occurs once for each element of the array. Each time through the loop, theLang has a different value picked from the array.

The reason this works in the Pig Latin game is this: When I used the Split() method on a string variable, it converted that variable to an array of strings. I could then use the foreach loop to step easily through that array. Closure at last…

Creating Tables with Two-Dimensional Arrays

The type of array you’ve seen so far in this chapter is used whenever you need to work with a list of data. Sometimes, however, you are more interested in more complex information. When you solve complex problems without a computer, you often find yourself keeping information in two-dimensional tables. C# supports a special two-dimensional array that allows you to work with this kind of information.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.116.36.194