Monday, July 22, 2013

Copying of Array1 to Array2 in C Sharp

Example to copy the Array1 to Array2 and print the details in C Sharp

//file name: demo_40
//Author: SURESH BABU
//Reference: Copying of array from another array

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

namespace demo_40
{
    class Program
    {
        static void Main(string[] args)
        {
            int[,] arr1 = new int[3, 3];
            int[,] arr2 = new int[3, 3];
            int i, j;

            // Storing User input in the Array

            for (i = 0; i < 3; i++)
            {
                for (j = 0; j < 3; j++)
                {
                    Console.WriteLine("Enter the Array Value:\t");
                    arr1[i, j] = Convert.ToInt32(Console.ReadLine());
                }
            }
            for (i = 0; i < 3; i++)
            {
                for (j = 0; j < 3; j++)
                {
                    arr2[i, j] = arr1[i, j];
                }
            }
            Console.Write("Elements of the Array2 = {");
            for (i = 0; i < 3; i++)
            {
             
                for (j = 0; j < 3; j++)
                {
                    Console.Write(" {0}", arr2[i, j]);
                }
            }
            Console.Write(" }");
            Console.ReadLine();
        }
    }
}

Jagged Arrays

In C Sharp: Jagged Arrays are described as it is collection of arrays of different or same number of elements in it but of similar type only.

Syntax of the Jagged Array
---------------------------

int[ ][ ] <<Jagged Array variable Name>  =  new int [ 2 ][ ];

int[ ][ ] jagged_array  =  new int [ 2 ][ ];

In above syntax, jagged_array is variable of Array data type, where it is having 2 Arrays in it.

Example:

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

namespace demo_20
{
    class Program
    {
        static void Main(string[] args)
        {

            //Declare two elements of the Array

            int[][] array = new int[2][];

            //filling the elements
            array[0] = new int[5] { 1, 3, 5, 7, 9 };
            array[1] = new int[4] { 2, 4, 6, 8 };

            //Display the array elements

            for (int i = 0; i < array.Length; i++)
            {
                Console.Write("Element of Array [{0}]: ", i);
                for (int j = 0; j < array[i].Length; j++)
                {
                    Console.Write("{0}{1}", array[i][j], j == (array[i].Length - 1) ? "" : "",i,j);
                }
                Console.WriteLine();
            }    

        }
    }
}