7/23/2010

C# Array (One Dimensional Array)



Arrays:
An array is a collection of homogeneous data element.
Types of arrays:
1. One dimensional array
2. Two dimensional array
3. Jagged array

One dimensional array
syntax:   data_type[] array_name = new data_type[size];


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Arrays
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Enter the number of elements");
            int n = int.Parse(Console.ReadLine());

            int []a=new int[n];
            
            Console.WriteLine("Enter " +n+" elements one by one");
            for (int i = 0; i < a.Length; i++)
                a[i] = int.Parse(Console.ReadLine());

            Console.WriteLine("Entered elements are");
            for (int j = 0; j < a.Length; j++)
                Console.WriteLine(a[j]);

            Array.Reverse(a);
            Console.WriteLine("Reversed elements are");
            for (int j = 0; j < a.Length; j++)
                Console.WriteLine(a[j]);

            Array.Sort(a);
            Console.WriteLine("Sorted elements are");
            for (int j = 0; j < a.Length; j++)
                Console.WriteLine(a[j]);

            Console.WriteLine("Enter the key element to be searched");
            int key = int.Parse(Console.ReadLine());

            Console.WriteLine("key element: " +key);

            int index=Array.BinarySearch(a, key);

            if (index > 0)
                Console.WriteLine(key + " present at the " + (index + 1) + " position");
            else
                Console.WriteLine(key + " not present in the list");
        }
    }
}

No comments:

Post a Comment