C# Arrays
C#

C# Arrays

C# Arrays refer to the collection of several values all belonging to the same data type. I will explain C# Arrays with a few simple examples. So, if even if you are not familiar with other programming languages, you will not have any difficulty in understanding. Let us discuss the declaration syntax first.

Array Declaration syntax in C#

In C# we can have, one-dimensional arrays, multi-dimensional arrays and the jagged arrays.

One Dimensional Array

Syntax: datatype[] array-name = new datatype[size];

Example: int[] myarr = new int[10];

Multi-Dimensional Arrays

Syntax: datatype[ , , …, ] = new datatype[size1, size2, …., sizen];

Example: int[ , ] m1 = new int[2,2]; //A two dimensional array

String [ , , ] = new String[2,3,4]; //A three dimensional array

Jagged Array

In C#, you can also create jagged arrays. We can have only two-dimensional jagged arrays in C#. In a jagged array, the number of columns need not be the same for each row. You can find more information on jagged arrays here.

Points to Remember
  1. In C#, memory allocation for Arrays is dynamic. Hence, we create arrays using the new keyword.
  2. In multidimensional arrays, the subscripts are specified within a single square bracket only, separated by a comma.
  3. The index of an array starts with 0.

Examples on C# Arrays

Example 1: Write a program to find the sum of all elements of an integer array. Also, find the minimum and maximum element in the array.

In this program, we create three non-static functions. The function arraysum() computes the sum of all array elements and returns it to the calling function Main(). The function, min_array() and max_array compute the minimum and maximum values respectively and return it to the Main(). All of these three functions take a one-dimensional array as input and return an int type value. Another point to note that, since these functions are non-static, we call them using the object of the class in which they are defined.

using System;

namespace ArrayExamples1
{
    class Program
    {
        static void Main(string[] args)
        {
            Program ob = new Program();
            int[] a = new int[10];
            Console.WriteLine("Enter 10 values: ");
            for(int i=0;i<10;i++)
            {
                a[i] = Int32.Parse(Console.ReadLine());
            }
            Console.WriteLine("Sum of array element =" + ob.arraysum(a));
            Console.WriteLine("Minimum value in array = " + ob.min_array(a));
            Console.WriteLine("Maximum value in array = " + ob.max_array(a));
            Console.ReadLine();
        }
        // function to find out the sum of array elements
        int arraysum(int[] arr)
        {
            int s = 0;
            for (int i = 0; i < arr.Length; i++)
            {
                s += arr[i];
            }
            return s;
        }
        // function to find out minimum value in array
        int min_array(int[] arr)
        {
            int m = arr[0];
            for(int i=1;i<arr.Length;i++)
            {
                if(m>arr[i])
                {
                    m = arr[i];
                }
           }
            return m;
        }
       // function to find out maximum value in array
        int max_array(int[] arr)
        {
            int m = arr[0];
            for(int i=1; i<arr.Length; i++)
            {
                if(m<arr[i])
                {
                    m = arr[i];
                }
            }
            return m;
        }
    }
}

Output:

C# Array Elements - Sum, Minimum and Maximum
C# Array Elements – Sum, Minimum and Maximum
Example 2: Write a program to create a new array by adding the specified value in each element of the given array.

This program illustrates an example of defining a non-static function in C#, which takes a one-dimensional integer array as an input parameter along with another integer value. Moreover, the function returns a 1D integer array as the return value. Specifically, the function increment_array(), creates a new array by adding the parameter value v to each of its elements.

using System;

namespace ArrayExamples1
{
    class Program
    {
        static void Main(string[] args)
        {
            Program ob = new Program();
            int[] a = new int[10];
            Console.WriteLine("Enter 10 values: ");
            for(int i=0;i<10;i++)
            {
                a[i] = Int32.Parse(Console.ReadLine());
            }
            int v;
            Console.WriteLine("Enter the increment value: ");
            v = Int32.Parse(Console.ReadLine());
            int[] a1 = ob.increment_array(a, v);

            Console.WriteLine("Original Array: ");
            foreach (int x in a)
            {
                Console.Write(x + " ");
            }
            Console.WriteLine("\nModified Array: ");
            foreach (int x in a1)
            {
                Console.Write(x + " ");
            }

       }
// function to increment each element of array with a given value // and return the modified array

        int[] increment_array(int[] arr, int v)
        {
            int[] arr1 = new int[10];
            for(int i=0;i<arr.Length;i++)
            {
                arr1[i] = arr[i] + v;
            }
            return arr1;
        }
    }
}
C# Arrays - Incrementing Each Element by a Given value
C# Arrays – Incrementing Each Element by a Given value
Example 3: Write a program to create an array by merging two given arrays.

Here I demonstrate an example of creating a new one-dimensional integer array by merging two arrays. Basically, the function merge_array() takes two 1D integer arrays as input, creates the merged array, and returns it. Remember that, the two input arrays must be sorted. The first while loop in the function compares the elements of two input arrays and assigns the minimum element to the resulting array. If elements are still remaining in any of the input arrays, the second and third while loops append them to the output array.

using System;
namespace ArrayExamples1
{
    class Program
    {
        static void Main(string[] args)
        {
            Program ob = new Program();
            int[] x1 = new int[5];
            int[] x2 = new int[5];

            Console.WriteLine("Enter elements of first array in sorted order: ");
            for (int i = 0; i < 5; i++)
            {
                x1[i] = Int32.Parse(Console.ReadLine());
            }
            Console.WriteLine("Enter elements of second array in sorted order: ");
            for (int i = 0; i < 5; i++)
            {
                x2[i] = Int32.Parse(Console.ReadLine());
            }

            int[] x3 = ob.merge_array(x1, x2);
            Console.WriteLine("\nMerged Array: ");
            foreach (int i in x3)
            {
                Console.Write(i + " ");
            }

       }
 // function to merge two arrays and create a third array
        int[] merge_array(int[] x1, int[] x2)
        {
            int[] x3 = new int[10];
            int i, j, k;
            i = 0;
            j = 0;
            k = 0;
            while((i<5) && (j<5))
            {
                if(x1[i]<x2[j])
                {
                    x3[k] = x1[i];
                    k++;
                    i++;
                }
                else
                {
                    x3[k] = x2[j];
                    k++;
                    j++;
                }
            }
            while(i<5)
            {
                x3[k] = x1[i];
                k++;
                i++;
            }
            while(j<5)
            {
                x3[k] = x2[j];
                k++;
                j++;
            }
            return x3;
        }

    }
}
C# Arrays - Merging Two Arrays
C# Arrays – Merging Two Arrays

To summarize, in this post three examples on C# Arrays are illustrated. The arrays are manipulated within the non-static functions, which we call by the objects of the class in which these functions are defined.


Related Topics

How to Create a Console Application inC#

C# Examples

Jagged Arrays in C#

Leave a Reply

Your email address will not be published. Required fields are marked *