Arrays

November2, 2017
by admin

In a simple definition, an array is a collection of elements having the same data type stored in sequence in contiguous memory location. Let’s discuss why to use arrays.

Suppose, you want to store marks for six subjects for a student. Basically, by normal variable use, we will declare six variables, each one for a single subject. That will be fine since number of variable to define is just six. But if you have a scenario where you want to store about 50 or 100 numbers, then rather than storing each value in a separate variable, we can use array for storing all numbers sequentially in a single array.

Let’s see how to do this by a simple example. Before that lets have a look at a definition of the array.

Syntax:

data_type[] array_variable;

Here, first we need to declare the data type for all the elements within the array. Remember that array stores all the elements of only same data type.

Note here a square bracket [] is post fixed with data type without space in between. This specifies the size of the array. Then we need to write the array name as a normal variable name.

Declaring and initializing array:

Ex:

int[] marks;
marks = new int[6] { 50,75, 67, 82, 73, 90 };

Here we have first declared marks array of data type int and then on the next line we have initialized it with marks for 6 subjects. Note that we have written the size of the array as 6 within the square bracket. The meaning of it is that marks array can store only up to 6 elements of integer data type. If we try to store more elements in array beyond the size of the array, then the compiler will
throw an error stating that the index is out of bound.

If you are not sure about the number of elements that are going to be stored in an array since it might get changed during the application flow then use the following initialization by omitting the size of the array.

Ex:

int[] marks;
marks = new int { 50,75, 67, 82, 73, 90 };

The array can be initialized at the time of declaration as follows.

Ex:

int[] marks = { 50,75, 67, 82, 73, 90 };

This way you don’t have to specify the size of the array.

Using or accessing the array elements:

The elements of the array are stored sequentially in the memory location. Any element can be accessed by using the index of an element.

The index of the first element is always zero, the second is 1, the third is 2 and so on in order.

The index of the last element is a number less than one of the total number of elements in an array. Suppose, we have six elements in above example of marks array, then the index of last element of marks array is 5 (6 – 1).

Accessing the first element of marks array:

marks[0];

Accessing the second element of marks array:

marks[1];

Accessing the last element of marks array:

marks[5];

Now lets look at the simple example of using arrays.

Ex:

Problem:

Write a program to calculate the total marks and percentage of 6 subjects obtained by a student and display to console output. Use proper messages when needed.

Solution:


  namespace ArrayDemo
  {
    class ArrayExample
    {
      static void Main(string[] args)
      {
        Console.WriteLine("Exam Result");

        // marks array
        int[] marks = { 50,75, 67, 82, 73, 90 };
  
        // variables to store total marks and percentage obtained
        int totalMarks = 0;
        double percentMarks = 0;

        // calculating total marks
        for(int x=0; x <=6; x++)
        {
          totalMarks = totalMarks + marks[x];
        }

        // calculating percentage obtained
        percentMarks = totalMarks / 6;

        // displaying result
        Console.WriteLine(string.Format("Total marks: {0}", totalMarks ));
        Console.WriteLine(string.Format("Marks percentage: {0}", percentMarks ));

        Console.WriteLine("Press any key to exit");
        Console.ReadKey();
      }
    }
  }

Output:

Total marks: 437

Marks percentage: 72.83

Code explanation:

On the first line of code within the main() function, we displayed heading 'Exam Result' with the following code.

Console.WriteLine("Exam Result");

Next, we declared and initialized array for marks obtained by a student. Note that we are hard coding the marks for 6 subjects here for the sake of simplicity. Instead, you can ask the user to enter every subject marks as an input.

int[] marks = { 50,75, 67, 82, 73, 90 };

Then we declared two variables, 'totalMarks' for storing the sum of marks of all 6 subjects and 'percentMarks' for storing the percentage obtained by the student. Note that the variable 'totalMarks' is of type int and the variable 'percentMarks' is of type double. Both these variables are initialized with value 0.

int totalMarks = 0;
double percentMarks = 0;

On next lines of code, we calculated the total marks of 6 subjects by adding them. For that we used looping concept and used 'for' loop since we know that we should repeat loop for 6 times for each subject once. We are adding marks from array elements to variable 'totalMarks' with each iteration of for loop so that at the end of the last iteration, we will have total marks for 6 subjects which are stored in the array.

for(int x=0; x <=6; x++)
{
  totalMarks = totalMarks + marks[x];
}

Note here how we accessed the marks for the current element of the array.

marks[x]; 

After calculating total marks for all subjects, we can calculate the percentage. So we wrote the following code to calculate it.

percentMarks = totalMarks / 6;

After calculating both total marks and percentage, it's time to show the result to the user by displaying it to console output. So we wrote the following code using string.Format() method which formats the string output.

Console.WriteLine(string.Format("Total marks: {0}", totalMarks ));
Console.WriteLine(string.Format("Marks percentage: {0}", percentMarks ));

After showing the result to the user, we simply asked the user to enter any key to stop the application using the following code.

Console.WriteLine("Press any key to exit");
Console.ReadKey();

Hope that you have now understood the basic concept of array and how to declare, initialize and access each elements from it.

C# Fundamentals