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.

Practical LearningPractical Learning: Introducing Arrays

  • Start Microsoft Visual C# and create a Console Application named VideoCollection1

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 keyword to create an array. The formula to use would be:

var VariableName = new DataType[Number];

In these formulas, the DataType factor 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 in Lesson 23. 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 declaring an array instead of a regular variable. The new operator allows the compiler to reserve memory. The Number factor 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
{
    static void Main()
    {
	double numbers = new double[5];
    }
}

Using the var keyword, this array can also be declared as follows:

using System;

public class Exercise
{
    static void Main()
    {
        var Numbers = new double[5];
    }
}

Practical LearningPractical Learning: Creating an Array

  1. To create arrays, change the Programs.cs file as follows:
     
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    
    namespace VideoCollection1
    {
        public class Program
        {
            static void Main(string[] args)
            {
                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];
            }
        }
    }
  2. Save the file

Introduction to Initializing an Array

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 0 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 void 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;
    }
}

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
{
    static void Main()
    {
        var Numbers = new double[5] { 12.44, 525.38, 6.28, 2448.32, 632.04 };
    }
}

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
{
    static void Main()
    {
        var Numbers = new double[] { 12.44, 525.38, 6.28, 2448.32, 632.04 };
    }
}

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

Practical LearningPractical Learning: Initializing Some Arrays

  1. To initialize the arrays, change the file as follows:
     
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    
    namespace VideoCollection1
    {
        class Program
        {
            static void Main(string[] args)
            {
                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
                };
            }
        }
    }
  2. Save the file
 

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
{
    static void Main()
    {
        var Area = 97394.2204D;
        var Distance = 982.84D;
        var Level = 27D;
        var Quantity = 237957.704D;

        var Measures = new double[] { Area, Distance, Level, Quantity };
    }
}

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

using System;

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

        var Measures = new double[] { PI, SqureRootOf2, e, RadiusOfEarth, ln2 };
    }
}

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
{
    static void 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
        };
    }
}

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
{
    static void Main()
    {
        var Red = 0xFF0000;
        var SomeColor = 0x800000;

        var Colors = new int[] { 2510, Red, 818203, SomeColor, 0xF28AC };
    }
}

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
{
    static void Main()
    {
        var FullTimeStudents = new bool[] { true, true, true, false, true, false };
    }
}

As stated already, each values 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
{
    static void Main()
    {
        var House1Value = 460885.85D;
        var House2Value = 685770.00D;

        var Conparisons = new bool[] { 25 < 10, House1Value == House2Value, true };
    }
}

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
{
    static void Main()
    {
        var DateHired = new DateTime(1998, 10, 08);
        var IndependenceDay = new DateTime(1960, 1, 1);

        var Dates = new DateTime[] { DateHired, IndependenceDay };
    }
}
 

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.

Practical LearningPractical Learning: Using the Members of an Array

  1. To show the values of a member of an array, change the Program.cs file as follows:
     
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    
    namespace VideoCollection1
    {
        class Program
        {
            static void Main(string[] args)
            {
                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.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("===============================");
            }
        }
    }
  2. Execute the application and test it. Here is an example:
     
    ===============================
    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. Close the DOS window

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.

Practical LearningPractical Learning: Using a for Loop

  1. To use a for loop, change the Program.cs file as follows:
     
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    
    namespace VideoCollection1
    {
        class Program
        {
            static void Main(string[] args)
            {
                . . . No Change
    
                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("===============================");
            }
        }
    }
  2. Execute the application to see the result:
     
    ===============================
    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
    ===============================
    Press any key to continue . . .

For Each Member in the Array

In a for loop, you should know the number of members of the array. If you don't, 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;
    using System.Linq;
    
    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;
    using System.Linq;
    
    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;
    using System.Linq;
    
    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;
using System.Linq;

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;
using System.Linq;

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;
using System.Linq;

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;
using System.Linq;

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 . . .

Practical LearningPractical Learning: Checking a Value From an Array

  1. To check a value from an array, change the file as follows:
     
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    
    namespace VideoCollection1
    {
        class Program
        {
            static void Main(string[] args)
            {
                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
                };
    
                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.WriteLine();
    
                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("===============================");
            }
        }
    }
  2. Execute the application to test it
  3. When prompted, enter a shelf number and press Enter. Here is an example:
     
    2985    8024    5170    1304    9187    1193    3082    8632    4633    9623
    Enter the shelf number of the video you want to check: 8632
    
    ===============================
    Video Information
    -------------------------------
    Shelf #:  8632
    Title:    Sneakers
    Director: Paul Alden Robinson
    Length:   126 minutes
    Rating:   PG-13
    Price:    9.95
    ===============================
    Press any key to continue . . .
  4. Close the DOS window and return to your programming environment
 

Previous Copyright 2008 FunctionX, Inc. Next