Array in C

From Logic Wiki
Jump to: navigation, search

Declaring Arrays

To declare an array in C#, you can use the following syntax:

datatype[] arrayName;

Initializing an Array

Declaring an array does not initialize the array in the memory. When the array variable is initialized, you can assign values to the array.

Array is a reference type, so you need to use the new keyword to create an instance of the array.

double[] balance = new double[10];

Assigning Values to an Array

You can assign values to individual array elements, by using the index number, like:

double[] balance = new double[10];
balance[0] = 4500.0;

You can assign values to the array at the time of declaration, like:

double[] balance = { 2340.0, 4523.69, 3421.0};

You can also create and initialize an array, like:

int [] marks = new int[5]  { 99,  98, 92, 97, 95};

In the preceding case, you may also omit the size of the array, like:

int [] marks = new int[]  { 99,  98, 92, 97, 95};

You can also copy an array variable into another target array variable. In that case, both the target and source would point to the same memory location:

int [] marks = new int[]  { 99,  98, 92, 97, 95};
int[] score = marks;

Using the foreach Loop In the previous example, we have 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);
           i++;
        }
        Console.ReadKey();
     }
  }
}