Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

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.

Saturday, January 29, 2011

Factorial and Fibonacci in C#



UPDATE: updated code examples and section using System.Numerics.BigInteger.

Here below a little program in C# that implements 2 classes (in fact, they are 3). There is the main class, called Fiborial (Fibo(nnacci)+(Facto)rial) that implements the Fibonacci and the Factorial algorithms in two ways, one Recursive (using recursion) and the other Imperative (using loops and states). The second class is just an instance class that does the same thing, but its there just to show the difference between static and instance classes, and finally the third one (which will not appear in other languages) is the Program class which has the static execution method "Main".

You can also find 3 more little examples at the bottom. One prints out the Factorial's Series and Fibonacci's Series, the second one just shows a class that mixes both: static and instance members, and finally the third one that uses different return types (including System.Numerics.BigInteger) for the Factorial method to compare the timing and result.

As with the previous posts, you can copy and paste the code below in your favorite IDE/Editor and start playing and learning with it. This little "working" program will teach you some more basics of the Programming Language.

There are some "comments" on the code added just to tell you what are or how are some features called. In case you want to review the theory, you can read my previous post, where I give a definition of each of the concepts mentioned on the code. You can find it here: http://carlosqt.blogspot.com/2011/01/new-series-factorial-and-fibonacci.html 


The Fiborial Program

// Factorial and Fibonacci in C#
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Numerics;

namespace FiborialCs
{
    // Static Class
    static class StaticFiborial
    {
        // Static Field
        static string className;
        // Static Constructor
        static StaticFiborial()
        {
            className = "Static Constructor";
            Console.WriteLine(className);            
        }
        // Static Method - Factorial Recursive
        public static BigInteger FactorialR(int n)
        {
            if (n == 1)
                return 1;
            else
                return n * FactorialR(n - 1);
        }
        // Static Method - Factorial Imperative
        public static BigInteger FactorialI(int n)
        {
            BigInteger res = 1;
            for (int i = n; i >= 1; i--)
            {                
                res *= i;
            }
            return res;
        }
        // Static Method - Fibonacci Recursive
        public static long FibonacciR(int n)
        {
            if (n < 2)
                return 1;
            else
                return FibonacciR(n - 1) + FibonacciR(n - 2);
        }
        // Static Method - Fibonacci Imperative
        public static long FibonacciI(int n)
        {            
            long pre, cur, tmp = 0;
            pre = cur = 1;            
            for (int i = 2; i <= n; i++)
            {
                tmp = cur + pre;
                pre = cur;
                cur = tmp;
            }
            return cur;
        }
        // Static Method - Benchmarking Algorithms
        public static void BenchmarkAlgorithm(int algorithm, List<int> values)
        {            
            Stopwatch timer = new Stopwatch();
            int i, testValue;
            BigInteger facTimeResult = 0;
            long fibTimeResult = 0;
            i = testValue = 0;            
            
            // "Switch" Flow Constrol Statement
            switch (algorithm)
            {
                case 1:
                    Console.WriteLine("\nFactorial Imperative:");
                    // "For" Loop Statement
                    for (i = 0; i < values.Count; i++)
                    {                        
                        testValue = values[i];
                        // Taking Time
                        timer.Start();
                        facTimeResult = FactorialI(testValue);
                        timer.Stop();                        
                        // Getting Time
                        Console.WriteLine(" ({0}) = {1}", testValue, timer.Elapsed);
                    }                    
                    break;
                case 2:
                    Console.WriteLine("\nFactorial Recursive:");
                    // "While" Loop Statement
                    while (i < values.Count)
                    {                        
                        testValue = values[i];
                        // Taking Time
                        timer.Start();
                        facTimeResult = FactorialR(testValue);
                        timer.Stop();
                        // Getting Time
                        Console.WriteLine(" ({0}) = {1}", testValue, timer.Elapsed);
                        i++;
                    }
                    break;
                case 3:
                    Console.WriteLine("\nFibonacci Imperative:");
                    // "Do-While" Loop Statement
                    do {
                        testValue = values[i];
                        // Taking Time
                        timer.Start();
                        fibTimeResult = FibonacciI(testValue);
                        timer.Stop();
                        // Getting Time
                        Console.WriteLine(" ({0}) = {1}", testValue, timer.Elapsed);
                        i++;
                    } while (i < values.Count);
                    break;
                case 4:
                    Console.WriteLine("\nFibonacci Recursive:");
                    // "For Each" Loop Statement
                    foreach (int item in values)
                    {
                        testValue = item;
                        // Taking Time
                        timer.Start();
                        fibTimeResult = FibonacciR(testValue);
                        timer.Stop();
                        // Getting Time
                        Console.WriteLine(" ({0}) = {1}", testValue, timer.Elapsed);
                    }
                    break;
                default:
                    Console.WriteLine("DONG!");
                    break;
            }                
        }
    }

    // Instance Class
    public class InstanceFiborial
    {
        // Instance Field
        string className;
        // Instance Constructor
        public InstanceFiborial()
        {
            this.className = "Instance Constructor";
            Console.WriteLine(this.className);
        }
        // Instance Method - Factorial Recursive
        public BigInteger FactorialR(int n)
        {
            // Calling Static Method
            return StaticFiborial.FactorialR(n);
        }
        // Instance Method - Factorial Imperative
        public BigInteger FactorialI(int n)
        {
            // Calling Static Method
            return StaticFiborial.FactorialI(n);
        }
        // Instance Method - Fibonacci Recursive
        public long FibonacciR(int n)
        {
            // Calling Static Method
            return StaticFiborial.FibonacciR(n);
        }
        // Instance Method - Factorial Imperative
        public long FibonacciI(int n)
        {
            // Calling Static Method
            return StaticFiborial.FibonacciI(n);
        }
    }

    public class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("\nStatic Class");
            // Calling Static Class and Methods
            // No instantiation needed. Calling method directly from the class
            Console.WriteLine("FacImp(5) = {0}", StaticFiborial.FactorialI(5));
            Console.WriteLine("FacRec(5) = {0}", StaticFiborial.FactorialR(5));
            Console.WriteLine("FibImp(11)= {0}", StaticFiborial.FibonacciI(11));
            Console.WriteLine("FibRec(11)= {0}", StaticFiborial.FibonacciR(11));

            Console.WriteLine("\nInstance Class");
            // Calling Instance Class and Methods 
            // Need to instantiate before using. Calling method from instantiated object
            InstanceFiborial ff = new InstanceFiborial();
            Console.WriteLine("FacImp(5) = {0}", ff.FactorialI(5));
            Console.WriteLine("FacRec(5) = {0}", ff.FactorialR(5));
            Console.WriteLine("FibImp(11)= {0}", ff.FibonacciI(11));
            Console.WriteLine("FibRec(11)= {0}", ff.FibonacciR(11));

            // Create a (generic) list of integer values to test
            // From 5 to 50 by 5
            List<int> values = new List<int>();
            for(int i = 5; i <= 50; i += 5)
                values.Add(i);

            // Benchmarking Fibonacci                     
            // 1 = Factorial Imperative            
            StaticFiborial.BenchmarkAlgorithm(1, values);
            // 2 = Factorial Recursive
            StaticFiborial.BenchmarkAlgorithm(2, values); 

            // Benchmarking Factorial            
            // 3 = Fibonacci Imperative
            StaticFiborial.BenchmarkAlgorithm(3, values);
            // 4 = Fibonacci Recursive
            StaticFiborial.BenchmarkAlgorithm(4, values); 

            // Stop and Exit
            Console.Read();
        }
    }
}

And the Output is:

































Humm, looks like Fibonnaci's algorithm implemented using recursion is definitively more complex than the others 3 right? I will grab these results for this and each of the upcoming posts to prepare a comparison of time execution between all the programming languages, then we will be able to talk about the algorithm's complexity as well.

Printing the Factorial and Fibonacci Series
using System;
using System.Text;
using System.Numerics;

namespace FiborialSeries
{    
    static class Fiborial
    {
        // Using a StringBuilder as a list of string elements
        public static string GetFactorialSeries(int n)
        {
            // Create the String that will hold the list
            StringBuilder series = new StringBuilder();
            // We begin by concatenating the number you want to calculate
            // in the following format: "!# ="
            series.Append("!");
            series.Append(n);
            series.Append(" = ");
            // We iterate backwards through the elements of the series
            for (int i = n; i <= n && i > 0; i--)
            {
                // and append it to the list
                series.Append(i);
                if (i > 1)
                    series.Append(" * ");
                else 
                    series.Append(" = "); 
            }
            // Get the result from the Factorial Method
            // and append it to the end of the list
            series.Append(Factorial(n));
            // return the list as a string
            return series.ToString();
        }

        // Using a StringBuilder as a list of string elements
        public static string GetFibonnaciSeries(int n)
        {
            // Create the String that will hold the list
            StringBuilder series = new StringBuilder();
            // We begin by concatenating the first 3 values which
            // are always constant
            series.Append("0, 1, 1");
            // Then we calculate the Fibonacci of each element
            // and add append it to the list
            for (int i = 2; i <= n; i++)
            {
                if (i < n)
                    series.Append(", ");
                else
                    series.Append(" = ");
                
                series.Append(Fibonacci(i));
            }
            // return the list as a string
            return series.ToString();
        }

        public static BigInteger Factorial(int n)
        {
            if (n == 1)
                return 1;
            else
                return n * Factorial(n - 1);
        }

        public static long Fibonacci(int n)
        {
            if (n < 2)
                return 1;
            else
                return Fibonacci(n - 1) + Fibonacci(n - 2);
        }
        
    }

    class Program
    {
        static void Main(string[] args)
        {            
            // Printing Factorial Series
            Console.WriteLine();
            Console.WriteLine(Fiborial.GetFactorialSeries(5));
            Console.WriteLine(Fiborial.GetFactorialSeries(7));
            Console.WriteLine(Fiborial.GetFactorialSeries(9));
            Console.WriteLine(Fiborial.GetFactorialSeries(11));
            Console.WriteLine(Fiborial.GetFactorialSeries(40));
            // Printing Fibonacci Series
            Console.WriteLine();
            Console.WriteLine(Fiborial.GetFibonnaciSeries(5));
            Console.WriteLine(Fiborial.GetFibonnaciSeries(7));
            Console.WriteLine(Fiborial.GetFibonnaciSeries(9));
            Console.WriteLine(Fiborial.GetFibonnaciSeries(11));
            Console.WriteLine(Fiborial.GetFibonnaciSeries(40));
        }
    }
}

And the Output is:

















Mixing Instance and Static Members in the same Class

We can also define instance classes that have both, instance and static members such as: fields, properties, constructors, methods, etc. However, we cannot do that if the class is marked as static because of the features mentioned in the previous post:
The main features of a static class are:
  • They only contain static members.
  • They cannot be instantiated.
  • They are sealed.
  • They cannot contain Instance Constructors

using System;
namespace FiborialExtrasCs2
{
    // Instance Classes can have both: static and instance members. 
    // However, Static Classes only allow static members to be defined.
    // If you declare our next example class as static
    // (static class Fiborial) you will get the following compile error
    // Error: cannot declare instance members in a static class
    
    // Instance Class
    class Fiborial
    {
        // Instance Field
        private int instanceCount;
        // Static Field
        private static int staticCount;        
        // Instance Read-Only Property
        // Within instance members, you can always use  
        // the "this" reference pointer to access your (instance) members.
        public int InstanceCount
        {
            get { return this.instanceCount; }
        }
        // Static Read-Only Property
        // Remeber that Properties are Methods to the CLR, so, you can also
        // define static properties for static fields. 
        // As with Static Methods, you cannot reference your class members
        // with the "this" reference pointer since static members are not
        // instantiated.        
        public static int StaticCount
        {
            get { return staticCount; }
        }
        // Instance Constructor
        public Fiborial()
        {
            this.instanceCount = 0;
            Console.WriteLine("\nInstance Constructor {0}", this.instanceCount);
        }
        // Static Constructor
        static Fiborial()
        {
            staticCount = 0;
            Console.WriteLine("\nStatic Constructor {0}", staticCount);
        }

        // Instance Method
        public void Factorial(int n)
        {
            this.instanceCount += 1;
            Console.WriteLine("\nFactorial({0})", n);
        }

        // Static Method
        public static void Fibonacci(int n)
        {
            staticCount += 1;
            Console.WriteLine("\nFibonacci({0})", n);
        }                
    }
    
    class Program
    {
        static void Main(string[] args)
        {
            // Calling Static Constructor and Methods
            // No need to instantiate
            Fiborial.Fibonacci(5);            

            // Calling Instance Constructor and Methods
            // Instance required
            Fiborial fib = new Fiborial();
            fib.Factorial(5);            

            Fiborial.Fibonacci(15);            
            fib.Factorial(5);

            // Calling Instance Constructor and Methods
            // for a second object
            Fiborial fib2 = new Fiborial();
            fib2.Factorial(5);
            
            Console.WriteLine();
            // Calling Static Property
            Console.WriteLine("Static Count = {0}", Fiborial.StaticCount);
            // Calling Instance Property of object 1 and 2
            Console.WriteLine("Instance 1 Count = {0}", fib.InstanceCount);
            Console.WriteLine("Instance 2 Count = {0}", fib2.InstanceCount);
        }
    }
}

And the Output is:





















Factorial using System.Int64, System.Double, System.Numerics.BigInteger

The Factorial of numbers over 20 are massive!
For instance: !40 = 815915283247897734345611269596115894272000000000!
Because of this, the previous version of this program was giving the "wrong" result
!40 = -70609262346240000 when using "long" (System.Int64) type, but it was not until I did the Fiborial version in VB.NET that I realized about this faulty code, because instead of giving me a wrong value, VB.NET execution thrown an Overflow Exception when using the "Long" (System.Int64) type.

My first idea was to use ulong and ULong, but both failed for "big" numbers. I then used Double (double floating point) type and got no more exception/wrong result. The result of the factorial was now correct !40 = 1.1962222086548E+56, but still I wanted to show the Integer value of it, so I did some research and found that there is a new System.Numerics.BigInteger class in the .NET Framework 4.0. Adding the reference to the project and using this new class as the return type of the Factorial methods, I was able to get the result I was expecting.
!40 = 815915283247897734345611269596115894272000000000

What I also found was that using different types change the time the algorithm takes to finish:
System.Int64 < System.Double < System.Numerics.BigInteger
Almost by double!

To illustrate what I just "tried" to say, lets have a look at the following code and the output we get.

using System;
using System.Numerics;
using System.Diagnostics;

namespace FiborialExtrasCs3
{
    class Program
    {
        static void Main(string[] args)
        {
            Stopwatch timer = new Stopwatch();
            System.Int64 facIntResult = 0;
            System.Double facDblResult = 0;
            System.Numerics.BigInteger facBigResult = 0;

            Console.WriteLine("\nFactorial using Int64");
            // Benchmark Factorial using Int64
            for (int i = 5; i <= 50; i += 5)
            {
                timer.Start();
                facIntResult = FactorialInt64(i);
                timer.Stop();
                Console.WriteLine(" ({0}) = {1} : {2}", i, timer.Elapsed, facIntResult);
            }
            Console.WriteLine("\nFactorial using Double");
            // Benchmark Factorial using Double
            for (int i = 5; i <= 50; i += 5)
            {
                timer.Start();
                facDblResult = FactorialDouble(i);
                timer.Stop();
                Console.WriteLine(" ({0}) = {1} : {2}", i, timer.Elapsed, facDblResult);
            }
            Console.WriteLine("\nFactorial using BigInteger");
            // Benchmark Factorial using BigInteger
            for (int i = 5; i <= 50; i += 5)
            {
                timer.Start();
                facBigResult = FactorialBigInteger(i);
                timer.Stop();
                Console.WriteLine(" ({0}) = {1} : {2}", i, timer.Elapsed, facBigResult);
            }
        }

        // Long Factorial 
        public static Int64 FactorialInt64(int n)
        {
            if (n == 1)
                return 1;
            else
                return n * FactorialInt64(n - 1);
        }

        // Double Factorial 
        public static Double FactorialDouble(int n)
        {
            if (n == 1)
                return 1;
            else
                return n * FactorialDouble(n - 1);
        }
        
        // BigInteger Factorial 
        public static BigInteger FactorialBigInteger(int n)
        {
            if (n == 1)
                return 1;
            else
                return n * FactorialBigInteger(n - 1);
        }
    }
}

NOTE: you need to manually add a reference to the System.Numerics assembly to your project so you can add it to your code.

And the Output is:

Monday, August 2, 2010

C# - Basics by Example



The first of a series of basics statements and constructs of .NET/JVM Programming Language is here! No boring step by step explanations... just code!
You can copy and paste the code below in your favorite IDE/Editor and start playing and learning with it. This little "working" program will teach you the basics of the Programming Language.

There are some "comments" on the code added just to tell you what are or how are some features called. In case you do not know the theory part, then you can read my previous post, where I give a definition of each of the concepts mentioned on the code. You can find it here: http://carlosqt.blogspot.com/2010/08/new-series-languages-basics-by-example.html 

Today's version of the Greetings Program is written in C# Enjoy!

Greetings Program - Verbose
// C# Basics
namespace CsGreetProgram
{
    using System;
    // Greeting Class
    internal class Greet  
    {  
        // Fields or Attributes
        private string message;
        private string name;
        private int loopMessage;
        // Properties
        public string Message
        {
            get { return this.message; }
            set { this.message = this.Capitalize(value); }
        }
        public string Name
        {
            get { return this.name; }
            set { this.name = this.Capitalize(value); }
        }
        public int LoopMessage
        {
            get { return this.loopMessage; }
            set { this.loopMessage = value; }
        }
        // Constructor
        public Greet() 
        {
            this.message = "";
            this.name = "";
            this.loopMessage = 0;
        }
        // Overloaded Constructor
        public Greet(string message, string name, int loopMessage)
        {
            this.message = this.Capitalize(message);
            this.name = this.Capitalize(name);
            this.loopMessage = loopMessage;
        } 
        // Method 1
        private string Capitalize(string val)
        {
            // "if-then-else" statement
            if (val.Length >= 1)
            {
                return val[0].ToString().ToUpper() + val.Substring(1, val.Length - 1);
            }
            else
            {
                return "";
            }
        }
        // Method 2
        public void Salute()  
        {
            // "for" statement
            for (int i = 0; i < this.loopMessage; i++)
            {
                Console.WriteLine("{0} {1}!", this.message, this.name);
            }
        }
        // Overloaded Method 2.1
        public void Salute(string message, string name, int loopMessage)
        {
            // "while" statement
            int i = 0;
            while(i < loopMessage)
            {
                Console.WriteLine("{0} {1}!", this.Capitalize(message), 
                                 this.Capitalize(name));
                i++;
            }
        }
        // Overloaded Method 2.2
        public void Salute(string name)
        {
            // "switch/case" statement
            DateTime dtNow = DateTime.Now;
            switch (dtNow.Hour)
            {
                case 6: case 7: case 8: case 9: case 10: case 11:
                    this.message = "good morning,";
                    break;
                case 12: case 13: case 14: case 15: case 16: case 17:
                    this.message = "good afternoon,";
                    break;
                case 18: case 19: case 20: case 21: case 22: 
                    this.message = "good evening,";
                    break;
                case 23: case 0: case 1: case 2: case 3: case 4: case 5: 
                    this.message = "good night,";
                    break;
                default:
                    this.message = "huh?";
                    break;
            }
            Console.WriteLine("{0} {1}!", this.Capitalize(this.message), 
                             this.Capitalize(name));
        }
    }
  
    // Console Program
    internal class Program  
    {                  
        public static void Main(string[] args)  
        {            
            // Define object of type Greet 
            Greet g;
            // Instantiate Greet. Call Constructor
            g = new Greet();
            // Call Set Properties
            g.Message = "hello";
            g.Name = "world";
            g.LoopMessage = 5;
            // Call Method 2
            g.Salute();
            // Call Overloaded Method 2.1 and Get Properties
            g.Salute(g.Message, "c#", g.LoopMessage);
            // Call Overloaded Method 2.2
            g.Salute("carlos");
            
            // Stop and exit
            Console.WriteLine("Press any key to exit...");
            Console.Read();
        }          
    }
}

Greetings Program - Minimal
// C# Basics
using System;
// Greeting Class
class Greet
{
    // Fields or Attributes
    string message, name;
    int loopMessage;
    // Properties
    public string Message
    {
        get { return message; }
        set { message = Capitalize(value); }
    }
    public string Name
    {
        get { return name; }
        set { name = Capitalize(value); }
    }
    public int LoopMessage
    {
        get { return loopMessage; }
        set { loopMessage = value; }
    }
    // Constructor
    public Greet()
    {
        message = "";
        name = "";
        loopMessage = 0;
    }
    // Overloaded Constructor
    public Greet(string message, string name, int loopMessage)
    {
        this.message = Capitalize(message);
        this.name = Capitalize(name);
        this.loopMessage = loopMessage;
    }
    // Method 1
    string Capitalize(string val)
    {
        // "if-then-else" statement
        if (val.Length >= 1)        
            return val[0].ToString().ToUpper() + val.Substring(1, val.Length - 1);
        else
            return "";
    }
    // Method 2
    public void Salute()
    {
        // "for" statement
        for (int i = 0; i < loopMessage; i++)
            Console.WriteLine("{0} {1}!", message, name);
    }
    // Overloaded Method 2.1
    public void Salute(string message, string name, int loopMessage)
    {
        // "while" statement
        int i = 0;
        while (i < loopMessage)
        {
            Console.WriteLine("{0} {1}!", Capitalize(message), 
                             Capitalize(name));
            i++;
        }
    }
    // Overloaded Method 2.2
    public void Salute(string name)
    {
        // "switch/case" statement
        DateTime dtNow = DateTime.Now;
        switch (dtNow.Hour)
        {
            case 6: case 7: case 8: case 9: case 10: case 11:
                message = "good morning,";
                break;
            case 12: case 13: case 14: case 15: case 16: case 17:
                message = "good afternoon,";
                break;
            case 18: case 19: case 20: case 21: case 22: 
                message = "good evening,";
                break;
            case 23: case 0: case 1: case 2: case 3: case 4: case 5: 
                message = "good night,";
                break;
            default:
                message = "huh?";
                break;
        }
        Console.WriteLine("{0} {1}!", Capitalize(message), 
                         Capitalize(name));
    }
}

// Console Program
class Program
{
    static void Main(string[] args)
    {
        // Define and Instantiate object of type Greet. Call Constructor
        Greet g = new Greet();              
        // Call Set Properties
        g.Message = "hello";
        g.Name = "world";
        g.LoopMessage = 5;
        // Call Method 2
        g.Salute();
        // Call Overloaded Method 2.1 and Get Properties
        g.Salute(g.Message, "c#", g.LoopMessage);
        // Call Overloaded Method 2.2
        g.Salute("carlos");        

        // Stop and exit
        Console.WriteLine("Press any key to exit...");
        Console.Read();
    }
}

And the Output is:

















Auto-Implemented Properties in C#

In C# 3.0 and later, auto-implemented properties make property-declaration more concise when no additional logic is required in the property accessors. They also enable client code to create objects. When you declare a property as shown in the following example, the compiler creates a private, anonymous backing field that can only be accessed through the property's get and set accessors. Taken from: http://msdn.microsoft.com/en-us/library/bb384054.aspx


/* That means that we can omit the Fields/Attributes declaration
   and go directly to the properties  */
        // private string message;
        // private string name;
        // private int loopMessage;
        // Auto-Implemented Properties
        public string Message
        {
            get; set;
        }
        public string Name
        {
            get; set;
        }
        public int LoopMessage
        {
            get; set;
        }

/* then, when ever you want to use them you get and set their value using the properties only/ Let's see an example in our constructor */
        // Constructor
        public Greet()
        {
        // error: Greet does not contain a definition for message/name/loopMessage
         // this.message = "";  
         // this.name = "";
         // this.loopMessage = 0;
         // We need to use the properties: 
            this.Message = "";  
            this.Name = "";
            this.LoopMessage = 0;
        }

Tuesday, June 15, 2010

OO Hello World - C#



So, here we go, the first of a series of hello world programs posts is here! And guess which language is the first one? C#. Why did I decide to show C# first? Well, basically because:

1. Is the most widely used programming language targeting the .NET CLR.
2. Is the one I use at work.
3. Is the one most of you already know, hence lets just show it and move on to the "less common" ones!

If you are new to C# you can jump to the second part of this post C# Info to get some extra info about the language, but don't forget to come back and see the code! :D

By the way, you can see my previous post here: http://carlosqt.blogspot.com/2010/06/oo-hello-world.html
where I give some details on WHY these "OO Hello World series" samples.

Version 1 (Minimal):
The minimum you need to type to get your program compiled and running.
using System;

class Greet
{
    string name;
    public Greet(string name)
    {
        this.name = name[0].ToString().ToUpper() + name.Substring(1, name.Length - 1);
    }
    public void Salute()
    {
        Console.WriteLine("Hello {0}!", name);
    }
}

// Greet the world!
class Program
{
    static void Main(string[] args)
    {
        Greet g = new Greet("world");
        g.Salute();
    }
}
Version 2 (Verbose):
Explicitly adding instructions and keywords that are optional to the compiler.
using System;
namespace GreetProgram
{
    internal class Greet
    {
        private string name;
        public Greet(string name)
        {
            this.name = name[0].ToString().ToUpper() + name.Substring(1, name.Length - 1);
        }
        public void Salute()
        {
            Console.WriteLine("Hello {0}!", this.name);            
        }
    }

    // Greet the world!
    internal class Program
    {                
        static void Main(string[] args)
        {
            Greet g = new Greet("world");
            g.Salute();            
        }        
    }
}

The Program Output:


 








C# Info:
“C# (pronounced "C sharp") is a programming language that is designed for building a variety of applications that run on the .NET Framework. C# is simple, powerful, type-safe, and object-oriented. The many innovations in C# enable rapid application development while retaining the expressiveness and elegance of C-style languages.” Taken from (http://msdn.microsoft.com/en-us/library/kx37x362.aspx)

Appeared:
2001
Current Version:
Developed by:
Microsoft
Creator:
Anders Hejlsberg
Influenced by:
C (Dennis Ritchie), C++ (Bjarne Stroustrup) and Java (James Gosling)
Predecessor Language

Predecessor Appeared

Predecessor Creator

Runtime Target:
CLR
Latest Framework Target:
4.0
Mono Target:
2.6
Allows Unmanaged Code:
Yes
Source Code Extension:
“.cs”
Keywords:
102
Case Sensitive:
Yes
Free Version Available:
Yes
Open Source:
No
Standard:
ECMA-334, ISO/IEC 23270
Latest IDE Support:
Visual Studio 2010 Express
SharpDevelop 3.2/4.0 (beta)
MonoDevelop 2.2
Language Reference:
Extra Info: