arrays_Element.md - brainchildservices/curriculum GitHub Wiki

Slide 1

Accessing Array Elements

An element is accessed by indexing the array name. This is done by placing the index of the element within square brackets after the name of the array. For example,

 double salary = balance[9];

The following example, demonstrates the above-mentioned concepts declaration, assignment, and accessing arrays −

 using System;

 namespace ArrayApplication {
    class MyArray {
       static void Main(string[] args) {
          int []  n = new int[10]; /* n is an array of 10 integers */
          int i,j;

          /* initialize elements of array n */
          for ( i = 0; i < 10; i++ ) {
             n[ i ] = i + 100;
          }
     
          /* output each array element's value */
          for (j = 0; j < 10; j++ ) {
             Console.WriteLine("Element[{0}] = {1}", j, n[j]);
          }
          Console.ReadKey();
       }
    }
 }

Slide 1 Downwards

When the above code is compiled and executed, it produces the following result −

 Element[0] = 100
 Element[1] = 101
 Element[2] = 102
 Element[3] = 103
 Element[4] = 104
 Element[5] = 105
 Element[6] = 106
 Element[7] = 107
 Element[8] = 108
 Element[9] = 109

Slide 2

Using the foreach Loop

In the previous example, we used a for loop for accessing each array element. You can also use a foreach statement to iterate through an array.

 using System;

 namespace ArrayApplication {
    class MyArray {
       static void Main(string[] args) {
          int []  n = new int[10]; /* n is an array of 10 integers */
     
          /* initialize elements of array n */
          for ( int i = 0; i < 10; i++ ) {
             n[i] = i + 100;
          }
     
          /* output each array element's value */
          foreach (int j in n ) {
             int i = j-100;
             Console.WriteLine("Element[{0}] = {1}", i, j);
          }
          Console.ReadKey();
       }
    }
 }

When the above code is compiled and executed, it produces the following result −

 Element[0] = 100
 Element[1] = 101
 Element[2] = 102
 Element[3] = 103
 Element[4] = 104
 Element[5] = 105
 Element[6] = 106
 Element[7] = 107
 Element[8] = 108
 Element[9] = 109