Home

Introduction to Arrays

   

A Series of Similar Items

 

Introduction

Imagine you want to create a program that would use a series of numbers. In algebra, we represent such a series as follows: X1, X2, X3, X4, X5. You can also represent a list of names as follows:

Alex
Gaston
Hermine
Jerry

So far, to use a series of items, we were declaring a variable for each of them. If the list was made of numbers, we would declare variables for such numbers as follows:

using System;

public class Exercise
{
    static int Main()
    {
        var number1 = 12.44;
        var number2 = 525.38;
        var number3 = 6.28;
        var number4 = 2448.32;
        var number5 = 632.04;

        return 0;
    }
}

Instead of using individual variables that share the same characteristics, you can group them in an entity like a regular variable. This group is called an array. Therefore, an array is a series of items of the same kind. It could be a group of numbers, a group of cars, a group of words, etc but all items of the array must be of the same type.

ApplicationApplication: Introducing Arrays

  1. Start Microsoft Visual Studio
  2. To create an application, on the main menu, click File -> New Project
  3. In the middle list, click Empty Project
  4. Set the Name to VideoCollection1
  5. Click OK

Array Creation

Before creating an array, you must first decide the type its items will be made of. Is it a group of numbers, a group of chairs, a group of buttons on a remote control? This information allows the compiler to know how much space each item of the group will require. This is because each item of the group will occupy its own memory space, just like any of the variables we have used so far.

After deciding about the type of data of each item that makes up the series, you must use a common name to identify them. The name is simply the same type of name you would use for a variable as we have used so far. The name allows you and the compiler to identify the area in memory where the items are located.

Thirdly, you must specify the number of items that will constitute the group. For the compiler to be able to allocate an adequate amount of space for the items of the list, once it knows how much space each item will require, it needs to know the number of items so an appropriate and large enough amount of space can be reserved. The number of items of an array is included in square brackets, as in [5].

An array is considered a reference type. Therefore, an array requests its memory using the new operator. Based on this, one of the formulas to declare an array is:

DataType[] VariableName = new DataType[Number];

Alternatively, you can use the var or the dynamic keyword to create an array. The formula to use would be:

var VariableName = new DataType[Number];
dynamic VariableName = new DataType[Number];

In these formulas, the DataType can be one of the types we have used so far (char, int, float, double, decimal, string, etc). It can also be the name of a class as we will learn. Like a normal variable, an array must have a name, represented in our formula as VariableName. The square brackets on the left of the assignment operator are used to let the compiler know that you are creating an array instead of a regular variable. The new operator allows the compiler to reserve memory. The Number is used to specify the number of items of the list.

Based on the above formula, here is an example of an array variable:

using System;

public class Exercise
{
    public static int Main()
    {
	double[] numbers = new double[5];
    }
}

Here are examples using the var or the dynamic keyword:

using System;

public class Exercise
{
    static int Main()
    {
        double[] numbers = new double[5];
        var distances = new float[8];
        dynamic values = new int[3];

        return 0;
    }
}

ApplicationApplication: Creating an Array

  1. To create a file, on the main menu, click Project -> Add New Item...
  2. In the middle list, click Code File
  3. Change the Name to VideoCollection and click Add
  4. In the empty document, type the following:
    public class VideoCollection
    {
        public static int Main()
        {
            long[]   shelfNumbers = new long[10];
            string[] titles = new string[10];
            string[] directors = new string[10];
            int[]    Lengths = new int[10];
            string[] ratings = new string[10];
            double[] prices = new double[10];
            
            return 0;
        }
    }

Introduction to the Array Class

To support arrays, the .NET Framework provides a class named Array. The Array class is defined in the System namespace. Whenever you create or use an array, it is actually an object of type Array. In this and the next two lessons, we will study what an array is, as a programming language concept. We will see the different ways you can use and manage an array. In Lesson 45, we will present more details about the Array class. We will find out that this class provides all the functionality necessary to create and manage an array.

Initializing an Array

 

Introduction

When creating an array, you can specify the number of items that make up its list. Each item of the series is referred to as a member or an element of the array. Once the array has been created, each one of its members is initialized with a default value. Most, if not all, of the time, you will need to change the value of each member to a value of your choice. This is referred to as initializing the array.

An array is primarily a variable; it is simply meant to carry more than one value. Like every other variable, an array can be initialized. There are two main techniques you can use to initialize an array. If you have declared an array as done above, to initialize it, you can access each one of its members and assign it a desired but appropriate value.

In algebra, if you create a series of values as X1, X2, X3, X4, and X5, each member of this series can be identified by its subscript number. In this case the subscripts are 1, 2, 3, 4, and 5. This subscript number is also called an index. In the case of an array also, each member can be referred to by an incremental number called an index. A C# (like a C/C++) array is zero-based. This means that the first member of the array has an index of 0, the second has an index of 1, and so on. In algebra, the series would be represented as X0, X1, X2, X3, and X4.

In C#, the index of a member of an array is written in its own square brackets. This is the notation you would use to locate each member. One of the actions you can take would consist of assigning it a value. Here is an example:

using System;

public class Exercise
{
    static int Main()
    {
        var numbers = new double[5];

        numbers[0] = 12.44;
        numbers[1] = 525.38;
        numbers[2] = 6.28;
        numbers[3] = 2448.32;
        numbers[4] = 632.04;

	return 0;
    }
}

The value between square brackets must be known. This time, we have used constants, but this is not always the case. The rule is that, at the time you open the square brackets, the value must be known, even if it is not a constant. For example, the value can be returned from a method. Here is an example:

using System;

public class Exercise
{
    static int GetIndex()
    {
        return 2;
    }

    public static int Main()
    {
        var numbers = new double[5];

        numbers[0] = 12.44;
        numbers[1] = 525.38;
        numbers[GetIndex()] = 6.28;
        numbers[3] = 2448.32;
        numbers[4] = 632.04;

	return 0;
    }
}

Besides this technique, you can also initialize the array as a whole when declaring it. To do this, on the right side of the declaration, before the closing semi-colon, type the values of the array members between curly brackets and separated by a comma. Here is an example:

using System;

public class Exercise
{
    public static int Main()
    {
        var numbers = new double[5] { 12.44, 525.38, 6.28, 2448.32, 632.04 };

	return 0;
    }
}

If you use this second technique, you don't have to specify the number of items in the series. In this case, you can leave all square brackets empty:

using System;

public class Exercise
{
    public static int Main()
    {
        var numbers = new double[] { 12.44, 525.38, 6.28, 2448.32, 632.04 };

	return 0;
    }
}

If you leave the square brackets empty, the compiler will figure out the number of items.

ApplicationApplication: Initializing Some Arrays

  • To initialize the arrays, change the file as follows:
    public class VideoCollection
    {
        public static int Main()
        {
            long[] shelfNumbers = new long[]
                {
                    2985, 8024, 5170, 1304, 9187,
                    1193, 3082, 8632, 4633, 9623
                };
            string[] titles = new string[]
                {
                    "The Distinguished Gentleman",
                    "A Perfect Murder", "Chalte Chalte",
                    "Ransom", "Not Another Teen Movie",
                    "Madhubaala", "Get Shorty",
                    "Sneakers", "Born Invincible", "Hush"
                };
            string[] directors = new string[]
                {
                    "Jonathan Lynn", "Andrew Davis", "Aziz Mirza",
                    "Ron Howard", "Joel Gallen", "Shivram Yadav",
                    "Barry Sonnenfeld", "Paul Alden Robinson",
                    "Unknown", "Jonathan Darby"
                };
            int[] lengths = new int[]
                {
                    112, 108, 145, 121, 100, 0, 105, 126,  90,  96
                };
            string[] ratings = new string[]
                {
                    "R", "R", "N/R", "R", "Unrated",
                    "N/R", "R", "PG-13", "N/R", "PG-13"
                };
            double[] prices = new double[]
                {
                    14.95D, 19.95D, 22.45D, 14.95D, 9.95D,
                    17.50D,  9.95D,  9.95D,  5.95D, 8.75D
                };
    
    	return 0;
        }
    }

The Length of an Array

We saw that if you declare an array variable but don't initialize it, you must specify the number of elements of the array. This number is passed inside the second pair of square brackets, as a constant integer. Here is an example:

using System;

public class Exercise
{
    static int Main()
    {
        var numbers = new double[5];

        return 0;
    }
}

If the array exists already, to assist you with finding out the number of elements in it, the Array class provides a read-only property named Length:

public int Length { get; }

Therefore, the know the number of items that an array contines, get the value of the Length property.

Other Techniques of Initializing an Array

We have initialized our arrays so far with values we specified directly in the curly brackets. If you have declared and initialized some variables of the same type, you can use them to initialize an array. Here is an example:

using System;

public class Exercise
{
    public static int Main()
    {
        var area = 97394.2204D;
        var distance = 982.84D;
        var level = 27D;
        var quantity = 237957.704D;

        var Measures = new double[] { area, distance, level, quantity };

	return 0;
    }
}

The values can also come from constant variables. Here is an example:

using System;

public class Exercise
{
    public static int Main()
    {
        const double PI = 3.141592653;
        var squareRootOf2 = 1.414D;
        var e = 2.718D;
        const double radiusOfEarth = 6370; // km
        var ln2 = 0.6931;

        var Measures = new double[] { PI, squareRootOf2, e, radiusOfEarth, ln2 };

	return 0;
    }
}

The values can also come from calculations, whether the calculation is from an initialized variable or made locally in the curly brackets. Here is an example:

using System;

public class Exercise
{
    public static int Main()
    {
        const double densityOfWater = 1000; // kg/m3 ;
        var massOfEarth = 5.98 * 10e24; // kg
        var earthMoonDistance = 2.39 * 10e5; // miles

        var Measures = new double[]
        {
            densityOfWater, 9.30 * 10.7, massOfEarth, earthMoonDistance
        };

	return 0;
    }
}

The rule to follow is that, at the time the array is created, the compiler must be able to know exactly the value of each member of the array, no guessing.

All of the arrays we have declared so far were using only numbers. The numbers we used were decimal constants. If the array is made of integers, you can use decimal, hexadecimal values, or a combination of both. Here is an example:

using System;

public class Exercise
{
    public static int Main()
    {
        var red = 0xFF0000;
        var someColor = 0x800000;

        var colors = new int[] { 2510, red, 818203, someColor, 0xF28AC };

	return 0;
    }
}

An array can have types of values of any of the data types we have used so far. The rule to follow is that all members of the array must be of the same type. For example, you can declare an array of Boolean values, as long as all values can be evaluated to true or false. Here is an example:

using System;

public class Exercise
{
    public static int Main()
    {
        var fullTimeStudents = new bool[] { true, true, true, false, true, false };

	return 0;
    }
}

As stated already, each value of a Boolean array must be evaluated to true or false. This means that you can use variables or expressions as members of the array. Here is an example:

using System;

public class Exercise
{
    public static int Main()
    {
        var house1Value = 460885.85D;
        var house2Value = 685770.00D;

        var conparisons = new bool[] { 25 < 10, house1Value == house2Value, true };

	return 0;
    }
}

As we will see when studying arrays and classes, you can use this technique to create an array of dates, times, or date and time values. Here is an example:

using System;

public class Exercise
{
    public static int Main()
    {
        var dateHired = new DateTime(1998, 10, 08);
        var independenceDay = new DateTime(1960, 1, 1);

        var Dates = new DateTime[] { dateHired, independenceDay };

	return 0;
    }
}

An index can be returned from a method. Here is an example:

using System;

public class Exercise
{
    static int GetIndex()
    {
        return 2;
    }

    static double GetDistance()
    {
        return 632.04;
    }

    public static int Main()
    {
        var numbers = new double[5];

        numbers[0] = 12.44;
        numbers[1] = 525.38;
        numbers[GetIndex()] = 6.28;
        numbers[3] = 2448.32;
        numbers[4] = GetDistance();

	return 0;
    }
}

As a result, both the index and the value can come from methods. Here is an example:

using System;

public class Exercise
{
    static int GetIndex()
    {
        return 4;
    }

    static double GetDistance()
    {
        return 632.04;
    }

    public static int Main()
    {
        var numbers = new double[5];

        numbers[0] = 12.44;
        numbers[1] = 525.38;
        numbers[2] = 6.28;
        numbers[3] = 2448.32;
        numbers[GetIndex()] = GetDistance();

	return 0;
    }
}

Accessing the Members of an Array

 

Introduction

After initializing an array, which means after each of its members has been given a value, you can access a member of the array to get, manipulate or even change its value. To access a member of the array, you use the square brackets as we saw above. As done for normal variables, one of the reasons of accessing a member of an array would be to display its value on the console screen, which can be done by passing it to a Console.Write() or a Console.WriteLine() method. Here is an example:

using System;

public class Exercise
{
    static int Main()
    {
        var numbers = new double[] { 12.44, 525.38, 6.28, 2448.32, 632.04 };

        Console.Write(numbers[3]);

        return 0;
    }
}

In the same way, you can use the curly brackets notation to display the value of a member:

using System;

public class Exercise
{
    static int Main()
    {
        var numbers = new double[] { 12.44, 525.38, 6.28, 2448.32, 632.04 };

        Console.Write("Number: {0} ", numbers[3]);

        return 0;
    }
}

In the same way, you can access 1, a few or all members of the array.

ApplicationApplication: Using the Members of an Array

  1. To show the values of a member of an array, change the VideoCollection.cs file as follows:
    using System;
    
    public class VideoCollection
    {
        public static int Main()
        {
            long[] shelfNumbers = new long[]
                {
                    2985, 8024, 5170, 1304, 9187, 1193, 3082, 8632
                };
    
                . . . No Change
    
            double[] prices = new double[]
                {
                    14.95D, 19.95D, 22.45D, 14.95D, 9.95D,
                    17.50D,  9.95D,  9.95D,  5.95D, 8.75D
                };
    
            Console.Title = "Video Collection";
    
            Console.WriteLine("===============================");
            Console.WriteLine("Video Information");
            Console.WriteLine("-------------------------------");
            Console.WriteLine("Shelf #:  {0}", shelfNumbers[1]);
            Console.WriteLine("Title:    {0}", titles[1]);
            Console.WriteLine("Director: {0}", directors[1]);
            Console.WriteLine("Length:   {0} minutes", lengths[1]);
            Console.WriteLine("Rating:   {0}", ratings[1]);
            Console.WriteLine("Price:    {0}", prices[1]);
            Console.WriteLine("===============================");
            
            Console.ReadKey();
            return 0;
        }
    }
  2. To execute the application, press F5:
    ===============================
    Video Information
    -------------------------------
    Shelf #:  8024
    Title:    A Perfect Murder
    Director: Andrew Davis
    Length:   108 minutes
    Rating:   R
    Price:    19.95
    ===============================
    Press any key to continue . . .
  3. Press Enter to close the DOS window and return to your programming environment

For an Indexed Member of the Array

We saw how you can use the square brackets to access each member of the array one at a time. That technique allows you to access one, a few, or each member. If you plan to access all members of the array instead of just one or a few, you can use the for loop. The formula to follow is:

for(DataType Initializer; EndOfRange; Increment) Do What You Want;

In this formula, the for keyword, the parentheses, and the semi-colons are required. The DataType factor is used to specify how you will count the members of the array.

The Initializer specifies how you would indicate the starting of the count. As seen in Lesson 12, this initialization could use an initialized int-based variable.

The EndOfRange specifies how you would stop counting. If you are using an array, it should combine a conditional operation (<, <=, >, >=, or !=) with the number of members of the array minus 1.

The Increment factor specifies how you would move from one index to the next.

Here is an example:

using System;

public class Exercise
{
    static int Main()
    {
        var numbers = new double[] { 12.44, 525.38, 6.28, 2448.32, 632.04 };

        for (var i = 0; i < 5; i++)
            Console.WriteLine(numbers[i]);

        return 0;
    }
}

This would produce:

12.44
525.38
6.28
2448.32
632.04
Press any key to continue . . .

When using a for loop, you should pay attention to the number of items you use. If you use a number n less than the total number of members - 1, only the first n members of the array would be accessed. Here is an example:

using System;

public class Exercise
{
    static int Main()
    {
        var numbers = new double[] { 12.44, 525.38, 6.28, 2448.32, 632.04 };

        for (var i = 0; i < 3; i++)
            Console.WriteLine("Number: {0}", numbers[i]);

        return 0;
    }
}

This would produce:

Number: 12.44
Number: 525.38
Number: 6.28
Press any key to continue . . .

On the other hand, if you use a number of items higher than the number of members minus one, the compiler would throw an IndexOutOfRangeException exception. Here is an example:

using System;

public class Exercise
{
    static int Main()
    {
        var numbers = new double[] { 12.44, 525.38, 6.28, 2448.32, 632.04 };

        for (var i = 0; i < 12; i++)
            Console.WriteLine("Number: {0}", numbers[i]);

        return 0;
    }
}

This would produce:

Error

After the nasty dialog box, you would get:

Index Out of Range Exception

Therefore, when the number of items is higher than the number of members - 1, the compiler may process all members. Then, when it is asked to process members beyond the allowed range, it finds out that there is no other array member. So it gets upset.

You could solve the above problem by using exception handling to handle an IndexOutOfRangeException exception. Here is an example:

using System;

public class Exercise
{
    static int Main()
    {
        var numbers = new double[] { 12.44, 525.38, 6.28, 2448.32, 632.04 };

        try
        {
            for (var i = 0; i < 12; i++)
                Console.WriteLine("Number: {0}", numbers[i]);
        }
        catch (IndexOutOfRangeException)
        {
            Console.WriteLine("You tried to access values beyond " +
                              "the allowed range of the members of the array.");
        }
        return 0;
    }
}

This would produce:

Number: 12.44
Number: 525.38
Number: 6.28
Number: 2448.32
Number: 632.04
You tried to access values beyond the allowed range of the members of the array.

Press any key to continue . . .

This solution should not be encouraged. Fortunately, C# and the .NET Framework provide better solutions.

ApplicationApplication: Using a for Loop

  1. To use a for loop, change the VideoCollection.cs file as follows:
    using System;
    
    public class VideoCollection
    {
        public static int Main()
        {
                . . . No Change
    
            Console.Title = "Video Collection";
    
            Console.WriteLine("=====================================");
            Console.WriteLine("Videos Information");
            for (int i = 0; i < 10; i++)
            {
                Console.WriteLine("=====================================");
                Console.WriteLine("Video {0}", i + 1);
                Console.WriteLine("-------------------------------------");
                Console.WriteLine("Shelf #:  {0}", shelfNumbers[i]);
                Console.WriteLine("Title:    {0}", titles[i]);
                Console.WriteLine("Director: {0}", directors[i]);
                Console.WriteLine("Length:   {0} minutes", lengths[i]);
                Console.WriteLine("Rating:   {0}", ratings[i]);
                Console.WriteLine("Price:    {0}", prices[i]);
            }
            Console.WriteLine("=====================================");
            
            Console.ReadKey();
            return 0;
        }
    }
  2. To execute the application and see the result, press F5:
    =====================================
    Videos Information
    =====================================
    Video 1
    -------------------------------------
    Shelf #:  2985
    Title:    The Distinguished Gentleman
    Director: Jonathan Lynn
    Length:   112 minutes
    Rating:   R
    Price:    14.95
    =====================================
    Video 2
    -------------------------------------
    Shelf #:  8024
    Title:    A Perfect Murder
    Director: Andrew Davis
    Length:   108 minutes
    Rating:   R
    Price:    19.95
    =====================================
    Video 3
    -------------------------------------
    Shelf #:  5170
    Title:    Chalte Chalte
    Director: Aziz Mirza
    Length:   145 minutes
    Rating:   N/R
    Price:    22.45
    =====================================
    Video 4
    -------------------------------------
    Shelf #:  1304
    Title:    Ransom
    Director: Ron Howard
    Length:   121 minutes
    Rating:   R
    Price:    14.95
    =====================================
    Video 5
    -------------------------------------
    Shelf #:  9187
    Title:    Not Another Teen Movie
    Director: Joel Gallen
    Length:   100 minutes
    Rating:   Unrated
    Price:    9.95
    =====================================
    Video 6
    -------------------------------------
    Shelf #:  1193
    Title:    Madhubaala
    Director: Shivram Yadav
    Length:   0 minutes
    Rating:   N/R
    Price:    17.5
    =====================================
    Video 7
    -------------------------------------
    Shelf #:  3082
    Title:    Get Shorty
    Director: Barry Sonnenfeld
    Length:   105 minutes
    Rating:   R
    Price:    9.95
    =====================================
    Video 8
    -------------------------------------
    Shelf #:  8632
    Title:    Sneakers
    Director: Paul Alden Robinson
    Length:   126 minutes
    Rating:   PG-13
    Price:    9.95
    =====================================
    Video 9
    -------------------------------------
    Shelf #:  4633
    Title:    Born Invincible
    Director: Unknown
    Length:   90 minutes
    Rating:   N/R
    Price:    5.95
    =====================================
    Video 10
    -------------------------------------
    Shelf #:  9623
    Title:    Hush
    Director: Jonathan Darby
    Length:   96 minutes
    Rating:   PG-13
    Price:    8.75
    =====================================
  3. Press Enter to close the DOS window and return to your programming environment

For Each Member in the Array

In a for loop, you should know the number of members of the array. If you do not, the C# language allows you to let the compiler use its internal mechanism to get this count and use it to know where to stop counting. To assist you with this, C# provides the foreach operator. To use it, the formula to follow is:

foreach (type identifier in expression) statement

The foreach and the in keywords are required.

The first factor of this syntax, type, can be var or the type of the members of the array. It can also be the name of a class as we will learn in Lesson 23.

The identifier factor is a name of the variable you will use.

The expression factor is the name of the array variable.

The statement is what you intend to do with the identifier or as a result of accessing the member of the array.

Like a for loop that accesses all members of the array, the foreach operator is used to access each array member, one at a time. Here is an example:

using System;

public class Exercise
{
    static int Main()
    {
        var numbers = new double[] { 12.44, 525.38, 6.28, 2448.32, 632.04 };

        foreach(var n in Numbers)
            Console.WriteLine("Number: {0} ", n);

        return 0;
    }
}

This would produce:

Employees Records
Employee Name: Joan Fuller
Employee Name: Barbara Boxen
Employee Name: Paul Kumar
Employee Name: Bertrand Entire

Anonymous Arrays

 

Introduction

In previous sections, when creating an array, we were specifying its type. As seen in our introduction to variables, a good feature of the var keyword is that, when using it to declare and initialize a variable, you ask the compiler to figure out what type of data the variable is holding. This concept is also valid for an array.

An anonymous array is an array variable whose type is left to the compiler to determine, based on the types of values of the array.

Creating an Anonymous Array

As done for variables so far, when creating an array, you can use the var keyword, initialize the array, but not specify its data type. The formula to use is:

var ArrayName = new[] { Initialization };

The formula is almost similar to that of a normal array, with keywords and operators you are already familiar with. The ArrayName factor is the name of the variable. Notice that the new keyword is directly followed by the square brackets. In the curly brackets, you must initialize the array by providing the necessary values. For the compiler to be able to figure out the type and amount of memory to allocate for the array variable, all values must be of the same type or the same category:

  • If each value is a number without a decimal part, the compiler checks their range and concludes whether the array needs 32 bits or 64 bits. Here is an example:
    using System;
    
    public class Exercise
    {
        static int Main()
        {
            var naturals = new[] { 2735, 20, 3647597, 3408, 957 };
            var values = new[] { 0x91FF22, 8168, 0x80080, 0xF822FF, 202684 };
    
            return 0;
        }
    }
  • If the values are numeric but at least one of them includes a decimal part, the compiler concludes that the array is made of floating-point numbers. If you want to control their precision (float, double, or decimal), add the appropriate suffix to each value. This also means that you can use a combination of natural and decimal numbers, but the presence of at least one number with a decimal part would convert the array into floating point instead of int-based. Here is an example:
    using System;
    
    public class Exercise
    {
        static int Main()
        {
            var singles = new[] { 1244F, 525.38F, 6.28F, 2448.32F, 632.04F };
            var doubles = new[] { 3.212D, 3047.098D, 732074.02, 18342.3579 };
            var values = new[] { 17.230M, 4808237M, 222.4203M, 948.002009M };
    
            return 0;
        }
    }
  • If the members are made of true and false values, then compiler will allocate memory for Boolean values for the array. Here is an example:
    using System;
    
    public class Exercise
    {
        static int Main()
        {
            var qualifications = new[] { true, true, false, true, false };
    
            return 0;
        }
    }
  • If the members contain values included in single-quotes, the array will be treated as a series of characters. Here is an example:
    using System;
    using System.Linq;
    
    public class Exercise
    {
        static int Main()
        {
            var categories = new[] { 'C', 'F', 'B', 'C', 'A' };
    
            return 0;
        }
    }
  • If the values of the members are included in double-quotes, then the array will be considered a group of strings. Here is an example:
    using System;
    using System.Linq;
    
    public class Exercise
    {
        static int Main()
        {
            var friends = new[] { "Mark", "Frank", "Charlotte", "Jerry" };
    
            return 0;
        }
    }

Accessing the Members of an Anonymous Array

After creating an anonymous array, you can access each member using its index. Here is an example that uses a for loop:

using System;
using System.Linq;

public class Exercise
{
    static int Main()
    {
        var friends = new[] { "Mark", "Frank", "Charlotte", "Jerry" };

        for (var i = 0; i < 4; i++)
            Console.WriteLine("Friend: {0}", friends[i]);

        return 0;
    }
}

This would produce:

Friend: Mark
Friend: Frank
Friend: Charlotte
Friend: Jerry
Press any key to continue . . .

In the same way, you can use a foreach statement to access each member of the array. Here is an example:

using System;

public class Exercise
{
    static int Main()
    {
        var friendlies = new[] { "Mark", "Frank", "Charlotte", "Jerry" };

        for (var i = 0; i < 4; i++)
            Console.WriteLine("Friend: {0}", friendlies[i]);
        Console.WriteLine("-----------------------------------");

        var qualifications = new[] { true, true, false, true, false };

        foreach (var qualifies in qualifications)
            Console.WriteLine("The Member Qualifies: {0}", qualifies);
        Console.WriteLine("-----------------------------------");

        return 0;
    }
}

This would produce:

Friend: Mark
Friend: Frank
Friend: Charlotte
Friend: Jerry
-----------------------------------
The Member Qualifies: True
The Member Qualifies: True
The Member Qualifies: False
The Member Qualifies: True
The Member Qualifies: False
-----------------------------------
Press any key to continue . . .

Selecting a Value From an Array

 

Introduction

Because an array is a list of items, it could include values that are not useful in all scenarios. For example, having an array made of too many values, at one time you may want to isolate only the first n members of the array, or the last m members of the array, or a range of members from an index i to an index j. Another operation you may be interested to perform is to find out if this or that value exists in the array. One more interesting operation would be to find out what members or how many members of the array respond to this or that criterion. All these operations are useful and possible with different techniques.

Using for and foreach

Consider the following program:

using System;

public class Exercise
{
    static int Main()
    {
        var numbers = new[] { 102, 44, 525, 38, 6, 28, 24481, 327, 632, 104 };

        for (var i = 0; i < 10; i++)
            Console.WriteLine("Number: {0}", numbers[i]);

        return 0;
    }
}

This would produce:

Number: 102
Number: 44
Number: 525
Number: 38
Number: 6
Number: 28
Number: 24481
Number: 327
Number: 632
Number: 104
Press any key to continue . . .

Imagine you want to access only the first n members of the array. To do this, you can use an if conditional statement nested in a for or a foreach loop. Here is an example that produces the first 4 values of the array:

using System;

public class Exercise
{
    static int Main()
    {
        var numbers = new[] { 102, 44, 525, 38, 6, 28, 24481, 327, 632, 104 };

        for (var i = 0; i < 10; i++)
            if (i < 4)
                Console.WriteLine("Number: {0}", numbers[i]);

        return 0;
    }
}

This would produce:

Number: 102
Number: 44
Number: 525
Number: 38
Press any key to continue . . .

You can use the same technique to get the last m members of the array. You can also use a similar technique to get one or a few values inside of the array, based on a condition of your choice. Here is an example that gets the values that are multiple of 5 from the array:

using System;

public class Exercise
{
    static int Main()
    {
        var numbers = new[] { 102, 44, 525, 38, 6, 28, 24481, 327, 632, 104 };

        for (var i = 0; i < 10; i++)
            if (numbers[i] % 5 == 0)
                Console.WriteLine("Number: {0}", numbers[i]);

        return 0;
    }
}

This would produce:

Number: 525
Press any key to continue . . .

ApplicationApplication: Checking a Value From an Array

  1. To check a value from an array, change the file as follows:
    using System;
    
    public class VideoCollection
    {
        public static int Main()
        {
            long[] shelfNumbers = new long[]
            {
                    2985, 8024, 5170, 1304, 9187,
                    1193, 3082, 8632, 4633, 9623
            };
            string[] titles = new string[]
            {
                    "The Distinguished Gentleman",
                    "A Perfect Murder", "Chalte Chalte",
                    "Ransom", "Not Another Teen Movie",
                    "Madhubaala", "Get Shorty",
                    "Sneakers", "Born Invincible", "Hush"
            };
            string[] directors = new string[]
            {
                    "Jonathan Lynn", "Andrew Davis", "Aziz Mirza",
                    "Ron Howard", "Joel Gallen", "Shivram Yadav",
                    "Barry Sonnenfeld", "Paul Alden Robinson",
                    "Unknown", "Jonathan Darby"
            };
            int[] Lengths = new int[]
            {
                    112, 108, 145, 121, 100, 0, 105, 126,  90,  96
            };
            string[] ratings = new string[]
            {
                    "R", "R", "N/R", "R", "Unrated",
                    "N/R", "R", "PG-13", "N/R", "PG-13"
            };
            double[] prices = new double[]
            {
                    14.95D, 19.95D, 22.45D, 14.95D, 9.95D,
                    17.50D,  9.95D,  9.95D,  5.95D, 8.75D
            };
    
            Console.Title = "Video Collection";
    
            foreach (int Code in shelfNumbers)
                    Console.Write("{0}\t", Code);
    
            long shelfNumber = 0;
    
            Console.Write("Enter the shelf number of the " +
    		      "video you want to check: ");
            shelfNumber = long.Parse(Console.ReadLine());
                
            Console.Clear();
    
            for (int i = 0; i < 10; i++)
            {
                if (shelfNumbers[i] == shelfNumber)
                {
                    Console.WriteLine("=====================================");
                    Console.WriteLine("Video Information");
                    Console.WriteLine("-------------------------------------");
                    Console.WriteLine("Shelf #:  {0}", shelfNumbers[i]);
                    Console.WriteLine("Title:    {0}", titles[i]);
                    Console.WriteLine("Director: {0}", directors[i]);
                    Console.WriteLine("Length:   {0} minutes", Lengths[i]);
                    Console.WriteLine("Rating:   {0}", ratings[i]);
                    Console.WriteLine("Price:    {0}", prices[i]);
                }
            }
            Console.WriteLine("=====================================");
            
            return 0;
        }
    }
  2. To execute the application to test it, press F5
  3. When prompted, enter a shelf number, such as 8632
    2985    8024    5170    1304    9187    1193    3082    8632    4633    9623
    Enter the shelf number of the video you want to check: 8632
  4. Press Enter. Here is an example:
    =====================================
    Video Information
    -------------------------------------
    Shelf #:  8632
    Title:    Sneakers
    Director: Paul Alden Robinson
    Length:   126 minutes
    Rating:   PG-13
    Price:    9.95
    =====================================
    Press any key to continue . . .
  5. Press Enter to close the DOS window and return to your programming environment
  6. Close your programming environment
  7. When asked whether you want to save, click No
 

Home Copyright © 2010-2011 FunctionX Next