Monday, July 1, 2013

Arrays and Indexers in C#



Today's post is about Arrays and Indexers in C#. Here below you will find a very easy to follow program, that demonstrate arrays and indexer, by implementing some simple tasks that will make you grasp the idea of those 2 features real quick. The main goal of this post, is not really teaching arrays because, come on, you probably already know "all" about them, in fact, it is more to show you how you do that in C#, in this case, compared to all other 22 languages on future posts, which essentially, is the real aim behind this blog.

By the way, if you missed my most recent post, "New Series - Arrays and Indexers", check it out. It has more details about the following program, and a bunch of definitions for the concepts used on this, and the following, posts.

Ok, enough talk, let's see C# version of the code.
I encourage you to copy the code below and try it yourself, normally, all programs you find in this blog are source code complete, just paste it on your IDE and run it.

Last thing. There is room for improvement of the code, using generics is one example, but Generics, Collections, lambdas, etc. will have their own "series" of posts.

using System;

namespace CsArrays
{
    class Program
    {
        static void Main(string[] args)
        {
            // Single-dimensional Array(s)
            PrintTitle("Reverse Array Elements");

            // Declare and Initialize Array of Chars
            char[] letters = new char[5];
            letters[0] = 'A';
            letters[1] = 'E';
            letters[2] = 'I';
            letters[3] = 'O';
            letters[4] = 'U';

            PrintArrayChar(letters);
            char[] inverse_letters = ReverseChar(letters);
            PrintArrayChar(inverse_letters);

            PrintTitle("Sort Integer Array Elements");

            // Declare and Initialize Array of Integers 
            int[] numbers = { 10, 8, 3, 1, 5 };
            PrintArrayInt(numbers);
            int[] ordered_numbers = BubbleSortInt(numbers);
            PrintArrayInt(ordered_numbers);

            PrintTitle("Sort String Array Elements");

            // Declare and Initialize and Array of Strings
            string[] names = new string[] {                     
                    "Damian", 
                    "Rogelio",
                    "Carlos", 
                    "Luis",                     
                    "Daniel"
                };
            PrintArrayString(names);
            string[] ordered_names = BubbleSortString(names);
            PrintArrayString(ordered_names);

            // Multi-dimensional Array (Matrix row,column)

            PrintTitle("Transpose Matrix");

            /* Matrix row=2,col=3
             * A =  [6  4 24]
             *      [1 -9  8]
            */
            int[,] matrix = new int[2, 3] { { 6, 4, 24 }, 
                                            { 1, -9, 8 } };
            PrintMatrix(matrix);
            int[,] transposed_matrix = TransposeMatrix(matrix);
            PrintMatrix(transposed_matrix);

            // Jagged Array (Array-of-Arrays)

            PrintTitle("Upper Case Random Array & Graph Number of Elements");

            /*             
             * Creating an array of string arrays using the String.Split method
             * instead of initializing it manually as follows:
             * 
             * string[][] text = new string[][] { 
             *      new string[] { "word1", "word2", "wordN" }, 
             *      new string[] { "word1", "word2", "wordM" }, 
             *      ...
             *      };
             * 
             * Text extract from: "El ingenioso hidalgo don Quijote de la Mancha"
             * 
             */
            string[][] text = { 
            "Hoy es el día más hermoso de nuestra vida, querido Sancho;".Split(' '),
            "los obstáculos más grandes, nuestras propias indecisiones;".Split(' '),
            "nuestro enemigo más fuerte, miedo al poderoso y nosotros mismos;".Split(' '),
            "la cosa más fácil, equivocarnos;".Split(' '),
            "la más destructiva, la mentira y el egoísmo;".Split(' '),
            "la peor derrota, el desaliento;".Split(' '),
            "los defectos más peligrosos, la soberbia y el rencor;".Split(' '),
            "las sensaciones más gratas, la buena conciencia...".Split(' ') 
            };
            PrintJaggedArray(text);
            UpperCaseRandomArray(text);
            PrintJaggedArray(text);
            GraphJaggedArray(text);

            // Array Exceptions

            PrintTitle("Common Array Exceptions");

            PrintCommonArrayExceptions(null);
            PrintCommonArrayExceptions(text);

            // Accessing Class Array Elements through Indexer

            PrintTitle("Alphabets");

            Alphabet vowels = new Alphabet(5);
            vowels[0] = 'a';
            vowels[1] = 'e';
            vowels[2] = 'i';
            vowels[3] = 'o';
            vowels[4] = 'u';

            Console.WriteLine("\nVowels = {{{0}}}",
                String.Join(",", vowels[0], vowels[1], vowels[2], vowels[3], vowels[4]));

            Alphabet en = new Alphabet("abcdefghijklmnopqrstuvwxyz");
            Console.WriteLine("English Alphabet = {{{0}}}", en.ToString());

            Console.WriteLine("Alphabet Extract en[9..19] = {{{0}}}", 
                          new Alphabet(en.Slice(9, 10)));

            string word1 = String.Join("", en[6], en[14], en[14], en[3]);
            string word2 = String.Join("", en[1], en[24], en[4]);
            string word3 = String.Join("", en[4], en[21], en[4], en[17],
                                           en[24], en[14], en[13], en[4]);

            Console.WriteLine("\n{0} {1}, {2}!\n", word1, word2, word3);

        }

        static char[] ReverseChar(char[] arr)
        {
            char[] reversed = new char[arr.Length];
            for (int i = 0, j = arr.Length - 1; j >= 0; i++, j--)
                reversed[i] = arr[j];
            return reversed;
        }

        static int[] BubbleSortInt(int[] arr)
        {
            int swap = 0;
            for (int i = arr.Length - 1; i > 0; i--)
            {
                for (int j = 0; j < i; j++)
                {
                    if (arr[j] > arr[j + 1])
                    {
                        swap = arr[j];
                        arr[j] = arr[j + 1];
                        arr[j + 1] = swap;
                    }
                }
            }
            return arr;
        }

        static string[] BubbleSortString(string[] arr)
        {
            string swap = "";
            for (int i = arr.Length - 1; i > 0; i--)
            {
                for (int j = 0; j < i; j++)
                {
                    if (arr[j][0] > arr[j + 1][0])
                    {
                        swap = arr[j];
                        arr[j] = arr[j + 1];
                        arr[j + 1] = swap;
                    }
                }
            }
            return arr;
        }

        static int[,] TransposeMatrix(int[,] m)
        {
            /* Transposing a Matrix 2,3 
             * 
             * A =  [6  4 24]T [ 6  1] 
             *      [1 -9  8]  [ 4 -9]
             *                 [24  8]
            */
            int[,] transposed = new int[m.GetUpperBound(1) + 1,
                                        m.GetUpperBound(0) + 1];
            for (int i = 0; i < m.GetUpperBound(0) + 1; i++)
            {
                for (int j = 0; j < m.GetUpperBound(1) + 1; j++)
                {
                    transposed[j, i] = m[i, j];
                }
            }
            return transposed;
        }

        static void UpperCaseRandomArray(string[][] arr)
        {
            Random r = new Random();
            int i = r.Next(0, arr.Length - 1);
            for (int j = 0; j <= arr[i].Length - 1; j++)
                arr[i][j] = arr[i][j].ToUpper();
        }

        static void PrintArrayChar(char[] arr)
        {
            Console.WriteLine("\nPrint Array Content {0}",
                arr.GetType().Name.Replace("]", arr.Length.ToString() + "]"));

            for (int i = 0; i <= arr.Length - 1; i++)
                Console.WriteLine(" array [{0,2}] = {1,2} ", i, arr[i]);
        }

        static void PrintArrayInt(int[] arr)
        {
            Console.WriteLine("\nPrint Array Content {0}",
                arr.GetType().Name.Replace("]", arr.Length.ToString() + "]"));

            for (int i = 0; i <= arr.Length - 1; i++)
                Console.WriteLine(" array [{0,2}] = {1,2} ", i, arr[i]);
        }

        static void PrintArrayString(string[] arr)
        {
            Console.WriteLine("\nPrint Array Content {0}",
                arr.GetType().Name.Replace("]", arr.Length.ToString() + "]"));

            for (int i = 0; i <= arr.Length - 1; i++)
                Console.WriteLine(" array [{0,2}] = {1,2} ", i, arr[i]);
        }

        static void PrintMatrix(int[,] m)
        {
            Console.WriteLine("\nPrint Matrix Content {0}[{1},{2}]",
                m.GetType().Name.Replace("[,]", ""),
                (m.GetUpperBound(0) + 1).ToString(),
                (m.GetUpperBound(1) + 1).ToString());

            for (int i = 0; i <= m.GetUpperBound(0); i++)
                for (int j = 0; j <= m.GetUpperBound(1); j++)
                    Console.WriteLine(" array [{0,2},{1,2}] = {2,2} ", i, j, m[i, j]);
        }

        static void GraphJaggedArray(string[][] arr)
        {
            /* When using Arrays, we can use foreach instead of for: 
             * 
             * for (int i = 0; i <= arr.Length - 1; i++)
             *   for (int j = 0; j <= arr.Length - 1; j++)                
             * 
            */
            Console.WriteLine("\nPrint Text Content {0}", arr.GetType().Name);
            int lineCount = 1;
            foreach (string[] s in arr)
            {
                Console.Write("Line{0,2}|", lineCount);
                foreach (string w in s)
                {
                    Console.Write("{0,3}", '*');
                }
                Console.WriteLine(" ({0})", s.Length);
                lineCount++;
            }
        }

        static void PrintJaggedArray(string[][] arr)
        {
            System.Text.StringBuilder line;
            Console.WriteLine("\nPrint Jagged Array Content {0}", arr.GetType().Name);
            for (int i = 0; i <= arr.Length - 1; i++)
            {
                line = new System.Text.StringBuilder();
                for (int j = 0; j <= arr[i].Length - 1; j++)
                    line.Append(" " + arr[i][j]);
                if (line.ToString() == line.ToString().ToUpper())
                    line.Append(" <-- [UPPERCASED]");
                Console.WriteLine(line);
            }
        }

        static void PrintCommonArrayExceptions(string[][] arr)
        {
            try
            {
                arr[100][100] = "hola";
            }
            catch (Exception ex)
            {
                Console.WriteLine("\nException: \n{0}\n{1}", ex.GetType().Name, ex.Message);
            }
        }

        static void PrintTitle(string message)
        {
            Console.WriteLine();
            Console.WriteLine("======================================================");
            Console.WriteLine("{0,10}", message);
            Console.WriteLine("======================================================");
        }

    }

    class Alphabet
    {
        // Array Field
        private char[] letters;

        // Indexer Get/Set Property 
        public char this[int index]
        {
            get { return letters[index]; }
            set { letters[index] = Char.ToUpper(value); }
        }

        // Read-Only Property
        public int Length
        {
            get { return this.letters.Length; }
        }

        // Constructors
        public Alphabet(int size)
        {
            this.letters = new char[size];
        }

        public Alphabet(string list)
        {
            this.letters = list.ToUpper().ToCharArray();
        }

        public Alphabet(char[] list)
        {
            this.letters = list;
        }

        // Overridden Method
        public override string ToString()
        {
            return String.Join(",", this.letters);
        }

        // Method
        public char[] Slice(int start, int length)
        {
            char[] result = new char[length];
            for (int i = 0, j = start; i < length; i++, j++)
            {
                result[i] = this[j];
            }
            return result;
        }

    }
}


The output:






















































































Voilà, that's it. Next post in the following days.

1 comment: