Topic : Arrays in C# Declaring Arrays | Initializing Arrays | Accessing Array Elements



Arrays:

An Array is a Variable with a single name that can store multiple values, but with each value indexed by a number. We can think of an Array as a numbered list where we can access elements by number.
Array is an Data Structure which can stores a fixed-size sequential collection of elements of the same type.



Arrays , Infobrother:

Array Can store fixed numbers of elements of the same data type sequentially in Memory. Therefore an integer Arrays holds some number of integers, a Character Array holds some number of characters, and so on. The size of Array is referred to as its dimension as shown in above figure.



Clear Your Concept:

Let's have an short Example to clear our concept of Arrays: in this example we will store the Result of 05 different students and will try to show all of them using Methods. in the Example there are two Methods. first is getData() Method, used to get all data from user. and the second is showData() Method, used to display all entered Data.



console.clear();

This Method is used to Clears the console buffer and corresponding console window of display information. This method is define in system Namespace. Using the Clear method is equivalent invoking the MS-DOS cls command in the command prompt window. When the Clear method is called, the cursor automatically scrolls to the top-left corner of the window and the contents of the screen buffer are set to blanks using the current foreground background colors.



/*Example: Arrays in C#: InfoBrother*/

using System;

namespace Arrays
{
    class Program
    {
        //static variable to use in our Methods:
        static int student1, student2, student3, student4, student5;

        public  void getData()  //method to get Data from user: 
        {

            Console.WriteLine("\nEnter Student Marks: ");
            student1 = Convert.ToInt32(Console.ReadLine());

            Console.WriteLine("\nEnter Student Marks: ");
            student2 = Convert.ToInt32(Console.ReadLine());

            Console.WriteLine("\nEnter Student Marks: ");
            student3 = Convert.ToInt32(Console.ReadLine());

            Console.WriteLine("\nEnter Student Marks: ");
            student4 = Convert.ToInt32(Console.ReadLine());

            Console.WriteLine("\nEnter Student Marks: ");
            student5 = Convert.ToInt32(Console.ReadLine());

            showData();   //method called to show Entered Data:
        }

        public  void showData()  //method to show Entered Data:
        {
            Console.Clear();  //clear the Screen:

            Console.WriteLine("student-1: " + student1);
            Console.WriteLine("student-2: " + student2);
            Console.WriteLine("student-3: " + student3);
            Console.WriteLine("student-4: " + student4);
            Console.WriteLine("student-5: " + student5);
        }

        static void Main(string[] args)
        {
            Program pro = new Program();  //Object creation:
            pro.getData();    //Function calling to get Data from user:
            Console.ReadKey();            
        }
    }
}


The Above program is absolutely Correct, it's produce the same result that we want. but the code is boring, we repeat same code again and again. we just add here only the result of 05 Student. but what's about if we Need to do same work for 1000 Students. do we Need to declare 1000 different variables, and repeat same code 1000 times. Yep we Have to do this if We don't Know about Arrays. Array don't let us bore by declaring variables having same types. Let's have a same example to show the student Result, But using Arrays: Let's see how Arrays make our life Easy:



/*Example: Arrays in C#: InfoBrother*/

using System;

namespace Arrays
{
    class Program
    {   
        static void Main(string[] args)
        {
            int [] N = new int[5];   //Array Declaration for 5 Integers:
            
            for(int i=0; i<5; i++) //Loop to get the data:
            {
                Console.WriteLine("Enter Student {0} Marks: ", i);
                N[i] = Convert.ToInt32(Console.ReadLine());         
            }

            Console.Clear();  //clear the screen:
            for (int i = 0; i < 5; i++) //loop to display the data:
            {
                Console.WriteLine("Student {0} Marks: {1} ", i, N[i]);
            }
            Console.ReadKey();
        }
    }
}


This is how Array help us to create Program Easily. An Array Name actually represents a memory address. when we declare an Array, we tell the compiler to use the Array name to indicate the beginning address of a Series of elements. For Example: if we declare an Array int [] N = new int[5]; we are telling the compiler (which is telling the operating system) to reserve memory locations for 5 integers beginning at the memory address that is represented by Array. (we will discuss about memory location in our "Data Structure" course for the time being just clear your concept about Array:) so let's move on:



Note That, In Programming, The counting is start from 0. so When we declare N[5], the index will move from 0 to 4:


Declaring Arrays:

To declare an Array in C#, We Use the Following Syntax:

dataType[]   arrayName;
//Example:

int[] Number;


  • In Above Syntax,

    » dataType is used to specify the type of Elements in The Array: if its int, we can store only integers, if its char, we can store only characters and so on...
    » [] Specifies the rank of the Array. The rank specifies the size of the array. like [10] will reserve the memory for only 10 integers:
    » arrayName specifies the Name of the Array. we can declare the name of array using the same rule as for variables.



Initializing an Array:

Declaring an Array does not initialize the Array in The Memory. When the Array variable is Initialized, we can assign values to the Array. Array is a reference type, so we need to use the New keyword to create an instance of the array.

int[]   Number =  new  int[5]  ;


Assigning Values to An Array:

We can assign values to individual array elements as Follow:


  • » Assigning Array Elements using Index Number:


    int [] Number = new int[5];  //declaration array:
    Number[4] = 35;   //store value in index 4th:


    » Assign values to Array at the time of Declaration: in This case we don't need to declare the size of array, The compiler will reserve memory for that elements itself:


    double[] Number = { 14.5, 25.3, 25.78 };


    » We can create and initialize an Array using this method too.


    int [] Number = new int[5] { 14, 15, 16, 17, 18 };


    » We can also use this method to declare and initialize the array. in This case we don't need to declare the size of array, The compiler will reserve memory for that elements itself:


    int [] Number = new int[] { 14, 15, 16, 17, 18 };


    » We can copy an array variable into another target array variable. In such case, both the target and source point to the same memory location:


    int [] Number = new int[] { 14, 15, 16, 17, 18 };
    int [] digits = Number;


    » We can initialize the Array using any loop too.


    int [] N = new int[5]; 
    for(int i=0; i<5; i++) 
        {
           Console.WriteLine("Enter Student {0} Marks: ", i);
           N[i] = Convert.ToInt32(Console.ReadLine());         
        }




When we create an array, C# compiler implicitly initializes each array element to a default value depending on the array type. For example: for an int array, all elements are initialized to 0.



Accessing Array Elements:

Once an Array is filled with useful values, we can access and use an individual array element in the same manner we would access and use any single variable of the same type. Any 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.


//Example:
int   Item = Element[ 7 ];


In the above statement, the Assignment (=) operator will assign the value of 7th Element of Array to variable "Item". Let's have an example here to know how we can access any Array element:



/*Example: Arrays in C#: InfoBrother*/

using System;

namespace Arrays
{
    class Program
    {   
        static void Main(string[] args)
        {
            int [] N = new int[5];   //Array Declaration for 5 Integers:
            
            for(int i=0; i<5; i++) //Loop to get the data:
            {
                Console.WriteLine("Enter Element-{0} ", i);
                N[i] = Convert.ToInt32(Console.ReadLine());         
            }

            //Access element using index Number:
            Console.WriteLine("\n // Access The Array Element: ");
            Console.WriteLine("Element[4] = {0}", N[4]);
            Console.WriteLine("Element[1] = {0}", N[1]);
            Console.WriteLine("Element[2] = {0}", N[2]);
            Console.WriteLine("Element[3] = {0}", N[3]);
            Console.WriteLine("Element[0] = {0}", N[0]);

            Console.ReadKey();
        }
    }
}
















I Tried my Best to Provide you complete Information regarding this topic in very easy and conceptual way. but still if you have any Problem to understand this topic, or do you have any Questions, Feel Free to Ask Question. i'll do my best to Provide you what you need.

Sardar Omar.
InfoBrother





WRITE FOR INFOBROTHER

Advertising






Advertisement