Chapter 10: Arrays

Quiz Solutions

Solution to Question 10-1. Arrays always begin with index (or offset) zero, so the seventh member of an array has index 6.

Solution to Question 10-2. No. Every array declares the type of objects it will hold. You can undermine this type safety by creating an array of Objects (which will hold anything, because everything derives from Object), but that is not advised.

Solution to Question 10-3. When you instantiate an array, you specify the number of elements in square brackets.

Solution to Question 10-4. Arrays are reference types and are created on the heap.

Solution to Question 10-5. The highest index in any array is always represented by Length - 1.

Solution to Question 10-6. You can explicitly call new or just imply the size of the array. For example, if you have three Employee objects named moe, larry, and curly:

Employee[] myEmpArray = new Employee[3] = { moe, larry, curly };

or:

Employee[] myEmpArray = { moe, larry, curly };

Solution to Question 10-7. There are a number of ways to iterate through the items in an array, but one of the most common is to use a for loop, using the loop’s control variable as the indexer in the array. An even simpler method is to use the foreach statement.

Solution to Question 10-8. The params keyword allows you to pass in an indefinite number of parameters, all of the same type, which will be treated as an array. You can, if you wish, also pass in an array.

Solution to Question 10-9. A rectangular array is a multidimensional array where each row has the same length. A jagged array is an array of arrays; the rows can be of unequal length.

Solution to Question 10-10. To arrange a random array of float values from greatest to least, you first call the Sort( ) method, and then the Reverse( ) method.

Exercise Solutions

Solution to Exercise 10-1. Declare a Dog class with two private members: weight (an int) and name (a string). Be sure to add properties to access the members. Then create an array that holds three Dog objects (Milo, 26 pounds; Frisky, 10 pounds; and Laika, 50 pounds). Output each dog’s name and weight.

The purpose of this exercise is simply to get you comfortable with using objects in arrays. The Dog class is quite simple to create, with its private members and getters and setters for each. All you have to do then is instantiate three Dog objects, instantiate the array, and assign the objects to the array (which you can do using the quick element initialization method, instead of using a loop). You’ll need a loop, either for or foreach, to output the values. Example A-22 shows one possible solution.

Example A-22. One solution to Exercise 10-1

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Exercise_10_1
{
    public class Dog
    {
        public Dog(int theWeight, string theName)
        {
            this.weight = theWeight;
            this.name = theName;
        }
        public int Weight
        {
            get
            {
                return weight;
            }
            set
            {
                weight = value;
            }
        }
        public string Name
        {
            get
            {
                return name;
            }
            set
            {
                name = value;
            }
        }
        private int weight;
        private string name;
    }
    public class Tester
    {
        public void Run(  )
        {
            Dog milo = new Dog(26, "Milo");
            Dog frisky = new Dog(10, "Frisky");
            Dog laika = new Dog(50, "Laika");
            Dog[] dogArray = { milo, frisky, laika };
            // output array values
            foreach (Dog d in dogArray)
            {
                Console.WriteLine("Dog {0} weighs {1} pounds.",
                                   d.Name, d.Weight);
            }
        }
        static void Main(  )
        {
            Tester t = new Tester(  );
            t.Run(  );
        }
    }
}

Solution to Exercise 10-2. Create an array of 10 integers. Populate the array by having the user enter integers at the console (use Console.Readline). Don’t worry about error checking for this exercise. Output the integers sorted from greatest to least.

Creating an array to hold 10 integers should be easy for you at this point. You’ll need to use a for loop to get the values of the 10 integers from the user. Once you have the array loaded, you have to call Sort( ) and then Reverse( ) on the array to sort the integers from greatest to least. Example A-23 shows one way of doing it.

Example A-23. One solution to Exercise 10-2

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Exercise_10_2
{
    public class Tester
    {
        public void Run(  )
        {
            int[] intArray = new int[10];
            Console.WriteLine("You'll be asked to enter 10 integers");
            // enter data into the array
            for (int i = 0; i < intArray.Length; i++)
            {
                Console.Write("Enter an integer: ");
                string theEntry = Console.ReadLine(  );
                intArray[i] = Convert.ToInt32(theEntry);
            }
            // sort and reverse the array
            Array.Sort(intArray);
            Array.Reverse(intArray);
            Console.WriteLine("
Values:");
            foreach (int j in intArray)
            {
                Console.WriteLine("{0}", j);
            }
        }
        static void Main(  )
        {
            Tester t = new Tester(  );
            t.Run(  );
        }
    }
}

Solution to Exercise 10-3. Extend Exercise 10-1 by creating a two-dimensional array that represents a collection of strings that indicate the awards each dog has won at dog shows. Each dog may have a different number of awards won. Output the contents of the array to check its validity.

You’re obviously going to need a two-dimensional array for this exercise. Since we told you that each dog may have won a different number of awards, you can tell it’s going to be a jagged two-dimensional array. The Dog class hasn’t changed any from the previous exercise, so there’s nothing to do there. You’ll have to create the new jagged array and populate it by hand. To output the contents of the array, you’ll need a pair of nested for loops. Example A-24 shows a possible solution.

Example A-24. One solution to Exercise 10-3

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Exercise_10_3
{
    public class Dog
    {
        public Dog(int theWeight, string theName)
        {
            this.weight = theWeight;
            this.name = theName;
        }
        public int Weight
        {
            get
            {
                return weight;
            }
            set
            {
                weight = value;
            }
        }
        public string Name
        {
            get
            {
                return name;
            }
            set
            {
                name = value;
            }
        }
        private int weight;
        private string name;
    }
    public class Tester
    {
        public void Run(  )
        {
            const int rows = 3;
            // declare and populate the dogs array
            Dog milo = new Dog(26, "Milo");
            Dog frisky = new Dog(10, "Frisky");
            Dog laika = new Dog(50, "Laika");
            Dog[] dogArray = { milo, frisky, laika };

            // declare the dogAwards array as 3 rows high
            string[][] dogAwardsArray = new string[rows][];

            // declare the rows
            dogAwardsArray[0] = new string[3];
            dogAwardsArray[1] = new string[1];
            dogAwardsArray[2] = new string[2];

            // Populate the rows
            dogAwardsArray[0][0] = "Best in Show";
            dogAwardsArray[0][1] = "Best of Breed";
            dogAwardsArray[0][2] = "Judge's Cup";
            dogAwardsArray[1][0] = "Best Toy Tog";
            dogAwardsArray[2][0] = "Best Working Dog";
            dogAwardsArray[2][1] = "Best Large Dog";

            // Output the contents
            for (int i = 0; i < dogAwardsArray.Length; i++)
            {
                Console.WriteLine("{0}'s awards: ", dogArray[i].Name);
                for (int j = 0; j < dogAwardsArray[i].Length; j++)
                {
                    Console.WriteLine("	{0}", dogAwardsArray[i][j]);
                }
            }
        }
        static void Main(  )
        {
            Tester t = new Tester(  );
            t.Run(  );
        }
    }
}

Solution to Exercise 10-4. Create a two-dimensional array that represents a chessboard (an 8-by-8 array). Each element in the array should contain the string “black” or the string “white,” depending on where it is on the board. Create a method that initializes the array with the strings. Then create a method that asks the reader to enter two integers for the coordinates of a square, and returns whether that square is black or white.

The interesting part of this exercise isn’t in returning the answer to the reader, it’s in setting up the board as a two-dimensional array. It’s pretty easy to imagine a chessboard as a two-dimensional array, where each element is either the string “white” or the string “black.” You also know that there will be only eight rows and eight columns (so you might as well make those constants). Let’s take one row at a time. If it’s an even-numbered row (if the row index % 2 is equal to zero), it starts with a black square. So, you assign every even-numbered square in that row the value of "black". Every square that isn’t assigned "black" is assigned "white". The next row has to start with a white square, so you’ll need an if/else to assign the opposite values to the next row. In the end, you’ll end up with an if/else inside a for loop, inside an if/else, inside a for loop, as shown in Example A-25.

Once you have the entire two-dimensional array created, it’s easy to take the user input and simply output the value of the string at those coordinates. Remember, though, that the user is entering a coordinate between 1 and 8, but the dimensions of the array range from 0 to 7, so when the user asks for the coordinates at (row, column), you’ll need to actually retrieve the value at chessboard[(row - 1), (column - 1)].

Example A-25. One solution to Exercise 10-4

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Exercise_10_4
{
    public class Tester
    {
        public void Run(  )
        {
            const int rows = 8;
            const int columns = 8;

            // create an 8x8 array
            string[,] chessboardArray = new string[rows, columns];

            // populate the chessboard array
            for (int i = 0; i < rows; i++)
            {
                // if row starts with a black square
                if ((i % 2) == 0)
                {
                    for (int j = 0; j < columns; j++)
                    {
                        if ((j % 2) == 0)
                        {
                            chessboardArray[i, j] = "black";
                        }
                        else
                        {
                            chessboardArray[i, j] = "white";
                        }
                    }
                }
                // else row starts with a white square
                else
                {
                    for (int j = 0; j < columns; j++)
                    {
                        if ((j % 2) == 0)
                        {
                            chessboardArray[i, j] = "white";
                        }
                        else
                        {
                            chessboardArray[i, j] = "black";
                        }
                    }
                }
            }

            // ask the user for coordinates to test
            Console.Write("Enter the row to test (1 through 8): ");
            string rowEntry = Console.ReadLine(  );
            int testRow = Convert.ToInt32(rowEntry);
            Console.Write("Enter the column to test (1 through 8): ");
            string colEntry = Console.ReadLine(  );
            int testCol = Convert.ToInt32(colEntry);

            // output the value at those coordinates
            Console.WriteLine("The square at {0}, {1} is {2}.", testRow,
            testCol, chessboardArray[(testRow - 1), (testCol - 1)]);
        }
        static void Main(  )
        {
            Tester t = new Tester(  );
            t.Run(  );
        }
    }
}
..................Content has been hidden....................

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