Sunday, 29 July 2012

Working With Arrays in C#



1            Arrays are reference types and are allocated memory on heap.
2            Every element of an array is automatically initialized to a default value based on its data type.
3            They are always dynamic because we can SET the size of the arrays at runtime.
4            Size of array can never be changed at runtime but we can create a new array with new length and copy the data from old array into new array.
5            Trying to access an element of array with invalid index throws IndexOutofRangeException Exception.
6            All arrays irrespective of their type are by default inherited from System. Array class
7            In C# we can have arrays of arrays and those are referred as Jagged Arrays. Here every element of the first array elements refers to another array and each one of them can be of different length


Single-Dimensional Arrays
int [] myArray = new int [5];
string []myStringArray = new string[5];

When you initialize an array upon declaration, it is possible to use the following shortcuts:
int[] myArray = {1, 3, 5, 7, 9};
string[] weekDays = {"Sun", "Sat", "Mon", "Tue"};

It is possible to declare an array variable without initialization, but you must use the new operator when you assign an array to this variable. For example:
int[] myArray;
myArray = new int[] {1, 3, 5, 7, 9};   // OK
myArray = {1, 3, 5, 7, 9};   // Error
weekdays = new string[] {“Sunday”, “Monday”, “Tuesday”};

Multi-Dimensional Arrays
int[,] myArray = new int[4,2];
Also, the following declaration creates an array of three dimensions, 4, 2, and 3:
int[,,] myArray = new int [4,2,3];
You can initialize the array upon declaration as shown in the following example:
int[,] myArray = new  int[,] {{1,2}, {3,4}, {5,6}, {7,8}};
You can also initialize the array without specifying the rank:
int[,] myArray = {{1,2}, {3,4}, {5,6}, {7,8}};
If you choose to declare an array variable without initialization, you must use the new operator to assign an array to the variable. For example:
int[,] myArray;
myArray = new int[,] {{1,2}, {3,4}, {5,6}, {7,8}};   // OK
myArray = {{1,2}, {3,4}, {5,6}, {7,8}};   // Error

Program to use arrays:
using System;
class Program
{
    static void Main(string[] args)
    {
        int[] ar = new int[] { 1, 2, 3, 4 };
        Console.WriteLine(ar.Length);
        Console.WriteLine(ar.Rank); //Prints Number of Dimensions in array.
        foreach (int n in ar)
            Console.WriteLine(n);
    }
}
Code: 3.9
C#


Program: To read a list of numbers separated by space and print the Average of all those numbers.
using System;
class ProgramForMaxOfAnyNumbers
{
    static void Main(string[] args)
    {
        string str = Console.ReadLine();
        string[] ar = str.Split(' ');
        int sum = 0;
        for (int i = 0; i < ar.Length; i++)
        {
            sum += int.Parse(ar[i]);
            Console.WriteLine(ar[i]);
        }
        Console.WriteLine("Average: " + 1.0 * sum / ar.Length);
    }
}
Code: 3.10
C#



Program: To read length and data for an array from keyboard print the same.
using System;
class ProgramForMaxOfAnyNumbers
{
    static void Main()
    {
        Console.Write("Enter the array length: ");
        int n;
        n = int.Parse(Console.ReadLine());
        int[] ar = new int[n];
        for (int i = 0; i < n; i++)
        {
            Console.Write("Enter the " + i + "th value: ");
            ar[i] = int.Parse(Console.ReadLine());
        }
        for (int i = 0; i < ar.Length; i++)
        {
            Console.Write(ar[i] + " ");
        }
    }
}
Code: 3.11
C#


----------------------------------------------------------------------------------------------------------------------------------
Tricky Question:
LETS SEE WHAT IS THE OUTPUT OF THE FOLLOWING PROGRAM
class Program
{
        static void Main(string[] args)
        {
            int[] mar1, mar2;
            mar1 = new int[] { 1, 2 };
            mar2 = new int[] { 1, 2 };
            Foo(mar1, ref mar2);
            Console.WriteLine(mar1[0] + " " + mar1[1]);
            Console.WriteLine(mar2[0] + " " + mar2[1]);
        }

        static void Foo(int[] ar1, ref int []ar2)
        {
            ar1[0]++;
            ar2[0]++;
        }
}

LETS KEEP THE DISCUSSION ON...
I WOULD REQUEST YOU TO RUN THE PROGRAM FIND THE ANSWER AND POST YOUR COMMENT WITH REASON...

I WILL PROVIDE THE REASON ONCE I HAVE SOME INPUTS HERE....

Loving You All.

Best of Luck.

12 comments:

  1. Simple
    1 2
    1 2
    Because we are just simply creating two arrays i.e mar1 and mar2 with some value and printing them. both of these arrays are referring to diff array.
    And the most important thing we are not calling that Foo() method any where in the Main(). so there is no chance of increment at all.

    ReplyDelete
    Replies
    1. Sorry, Foo should have been called...Please try now.

      Delete
  2. No overload for method Foo takes 0 arguements

    ReplyDelete
  3. if foo method shld be called,, we need to be remove reference

    ReplyDelete
  4. The output is
    2 2
    2 2
    Foo(mar1, ref mar2);in this the mar1 is the reference to that array mar1 (which is on Heap) and its ref is in mar1.
    So in Foo() using that ref we are accessing that array and changing the value. Here array copy is not send to Foo().Rather ref to that array is send.

    ReplyDelete