Back to Top

An Introduction to C# Arrays


Welcome to a new tutorial! This time we will play with arrays, which can store several values in a single variable. That feature helps us keep our code simple and flexible.


Here's an example: let's assume that you need to compute the average age of three people. You could use something like this.


        float age1 = 20f;

        float age2 = 38f;

        float age3 = 27f;

        float average;

        private void button1_Click(object sender, EventArgs e)

        {

            average = (age1 + age2 + age3) / 3;

            textBox1.Text = average.ToString();

        }


The code above will work, but can you imagine what would happen if you needed to compute the average for 100 people? By making use of an array, we can simplify the code a lot.


Start a new Windows Forms App project, name it "Arrays", and then add a button and a TextBox to the form. Double click the button to launch its method, and then add the code highlighted below to the source file.


averageRun the project, click the button, and you will see that the application computes the average age and displays it.


Please note how we access the array elements; myAges[0] will give us access to the first element in the array, myAges[1] refers to the second element, and so on.


Each array needs to use a pair of parentheses. Here's how you can populate a string array which stores several names.


myFriends = new string[] { "Bill", "Jane", "Robert", "Bert", "Mary" };


Then, you can display any names in the array using myFriends[0] to get access to "Bill", myFriends[2] for "Robert", etc.


Type in the code below to try a simple snippet which declares an array, populates it, and then displays its 3rd element on the screen.


arraysBesides reading values, you can also change them in any array by using something like this:


myFriends[2] = "Jim"; // Robert has been replaced with Jim


Finally, we can loop through arrays, accessing all their elements. Here's the code for a more advanced application, which determines the number of array elements automatically, and then reads all the values, computing their average.


advancedLet's discuss what happens here.

       float[] myAges = {20f, 38f, 27f, 44f, 12f, 80f, 51f};

        float sum = 0f, average;


The variable declarations above are quite common; take a good look at the second line of code, though, and you will discover that we have declared two variables (sum and average) using a single line of code, and we have initialized the first one.


        private void button1_Click(object sender, EventArgs e)

        {

            for (int i = 0; i < myAges.Length; i++)

            {

                sum += myAges[i];

            }

            // we've got the total here, so let's compute the average

            average = sum / myAges.Length;

            textBox1.Text = average.ToString(); // displays the average age

        }


The button code uses a "for" loop, which will repeat the action specified within its pair of brackets for as long as the condition specified within the parentheses stays true. The loop will start with i = 0 and do its job, adding the values stores inside myAges[] to the "sum" variable until it has reached the total number of array elements - that's what the Length property does. This means that you can add or delete array elements inside "myAges" to your liking, and the code will continue to do its job properly.


When the loop is over, sum stores the total, which will be divided by the number of array elements to give us the average age value.


The tutorial ends here, but don't forget that if you like my coding style and explanations, I would be delighted to work with you. I hope to hear from you soon!