Showing posts with label Data Structures. Show all posts
Showing posts with label Data Structures. Show all posts

Saturday, January 2, 2016

C# : Implementation of List using C#

How to implement List in C#


If you ever had the opportunity to learn C or C++, you must be very comfortable with the concepts of Linked List . C# goes further and provides you with a data structure called List.  The list data structure is one of the most used data structures in any programming language and it is evident from the fact that every modern language, let it be Java, Python, etc ... support the List Data Structure. Hence having the concepts of List in your bag will make you an even complete Programmer. There will be various situations where you would love to use lists. Some of them may be : 

  • Making a Playlist when you make a Media Player Application.
  • Making a list of Recipes if you are making a Cooking Application.
  • Showing the rows fetched from a Database in the form of a list.
  • Showing the products in a list if you make an E-Commerce Application.
  • And at many countless places ...
In short, a list is an Abstract Data Type that represents an ordered  sequence of values. Some of the operations that you can directly perform on a list in C# are :

  • To check whether the list is empty or not.
  • To add an item to the list.
  • To count the number of items in the list.
  • To remove an item from the list at any index (first , last , middle, at any index).
  • To sort the items in the list.
  • To search for an element in the list.
  • To  find the average of values/items in the list.
  • To remove all the elements of list at once.
  • To find the maximum value in a list.
  • To find the minimum value of a list.
  • To set the capacity of the list (i.e. the number of items it can hold).
  • And many other operations (Thanks to C# :) ) .

Let us directly jump to the implementation of the list.

Step 1:  Open Visual Studio Professional 2015



Step 2:  Click on New Project. Select Console Application and give desired Name to the application



Step 3:  Click on OK and you will get the following Screen



Step 4The overall implementation or the code should like the following.

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

namespace ListConsoleExample
{
    class Program
    {
        static void Main(string[] args)
        {
            // Main Method
            // In this example we will see basic implementation of Data Structure:List 
            // using the language C#.

            //Declaring a List of integers 
            //(You can make List of other Data Types as you want e.g string,etc..)
            List<int> testList = new List<int>();

            //Adding elements to the end of List
            Console.WriteLine("Adding elements to the end of list");
            for (int i = 0; i < 6; i++)
            {
                testList.Add(i+1);
            }
            Console.WriteLine("Adding of Elements to the List is finished");
            
            // Accessing any element from the list using the index
            Console.WriteLine("Element in List at index 5 is : " + testList[5]);
            
            Console.WriteLine("Iterating through the List and printing the value");

            for (int i = 0; i < 6; i++)
            {
             Console.WriteLine("Element in List at index " +  i + " is : " + testList[i]);
            }
            Console.WriteLine("Iterating through the List is finished");

            // Removing any element from the list using index
            Console.WriteLine("Removing element 3 from the List");
            testList.RemoveAt(3);
            Console.WriteLine("Element at index 3 removed from the List");

            testList.Add(0);
            Console.WriteLine("Before Sorting :");

            foreach(int item in testList)
            {
                Console.WriteLine("The item is : " + item);
            }
            //Sorting the list
            testList.Sort();

            Console.WriteLine("After Sorting :");

            foreach (int item in testList)
            {
                Console.WriteLine("The item is : " + item);
            }

            // Waiting for enter to be pressed by user to prevent the Console Screen from 
            // closing automatically
            Console.ReadLine();
        }
    }
}
  

Step 4The output for the above code should like the following.:




Let us know if you liked the article through your comments and feedback . Cheers!! 

Sunday, December 20, 2015

C#: Implementation of Dictionary using C#

How to implement a Dictionary using C# 


Dictionary in C# is a pretty cool data structure. In very simple words, you have a key-value pair, and these multiple key-value pairs make up the dictionary. The most important thing to note here is that you can access any value directly by using its key. The various operations performed on dictionary are:
  • The addition of pairs to the collection.
  • The removal of pairs from the collection.
  • The modification of the values of existing pairs.
  • The lookup of the value associated with a particular key.

Let us get acquainted with its definition first.

Definition

A Dictionary in C# is used to represent a collection of keys and values pair of data.

The following image shows the basic representation of a key value pair.

Image Source: scraping.pro

Key - Value Pair Example



Now if you want to access the value John, you can directly access it using the key User2.

Applications of Dictionary

  • The simplest examples that comes to mind is JSON, which is nothing but a collection of key - value pairs.
  • Secondly, Dictionaries are also used in Search Engines and Machine Learning.
 Now  let's see how this is implemented in C#.

Step 1:  Open Visual Studio Professional 2015



Step 2:  Click on New Project. Select Console Application and give desired Name to the application


Step 3:  Click on OK and you will get the following Screen




Step 4The overall implementation or the code should like the following.

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

namespace DictionaryConsoleExample
{
    class Program
    {
        static void Main(string[] args)
        {
            // Main Method
            // In this example we will see basic implementation of Data Structure -
            // Dictionary using the language C#.

            //Declaring a Dictionary which has keys as string and values as integer 
            //(You can make other types of Dictionaries as you want)
            Dictionary<String, int> testDictionary = new Dictionary<string, int>();

            //Inserting Key Value Pairs to the Dictionary
            Console.WriteLine("Inserting Key Value Pairs to the Dictionary");
            for (int i = 0; i < 10; i++)
            {
                testDictionary.Add("Number " + i, i);
            }
            Console.WriteLine("Adding of key value pairs to the Dictionary is finished");

            // We can directly access any element of the Dictionary using keys 
   
            Console.WriteLine("Printing the value whose key is \" Number 3\" :");

            Console.WriteLine("Value using \" Number 3 \" Key is : " + testDictionary["Number 3"]);

            // Waiting for enter to be pressed by user to prevent the Console Screen from 
            // closing automatically.
            Console.ReadLine();
        }
    }
}



Output: The output would like this:




Hope you liked the article. Let us know your feedback and questions through comments. Cheers!!

Friday, December 18, 2015

C# : Implementation of Queue using C#

How to implement Queue using C#


Queue is one of the most used data structures in Computer programming and understanding how queues work is essential for learning Data Structures thoroughly. Let us see the definition first :

 Definition : According to Wikipedia, 


" In Computer Science, a queue is a particular kind of abstract data type or collection in which the     entities in the collection are kept in order and the principal (or only) operations on the collection are the addition of entities to the rear terminal position, known as enqueue, and removal of entities from the front terminal position, known as dequeue. This makes the Queue a First-In-First-Out (FIFO) data structure. In a FIFO data structure, the first element added to the queue will be the first one to be removed. This is equivalent to the requirement that once a new element is added, all elements that were added before have to be removed before the new element can be removed. " 


The following image illustrates the concept of a Queue:

Image Source : http://jcsites.juniata.edu/

Image showing a typical Queue (real world example)

Typical use of Queues is in Operating Systems, some of the applications of Queue are listed below:


  • Operating systems often maintain a queue of processes that are ready to execute or that are waiting for a particular event to occur.


  • Computer systems must often provide a “holding area” for messages between two processes, two programs, or even two systems. This holding area is usually called a “buffer” and is often implemented as a queue.



  • Now let us go to the step by step implementation of the Queue Data Structure.We are using Visual Studio 2015 for the implementation.

    Step 1:  Open Visual Studio Professional 2015




    Step 2:  Click on New Project. Select Console Application and give desired Name to the application.




    Step 3:  Click on OK and you will get the following Screen



    Step 4The overall implementation or the code should like the following.



    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    
    namespace QueueConsoleExample
    {
        class Program
        {
            static void Main(string[] args)
            {
                // Main Method
                // In this example we will see basic implementation of Data Structure: Queue 
                // using the language C#.
    
                //Declaring a Queue of integers 
                //(You can make Queues of other Data Types as you want)
                Queue<int> testQueue = new Queue<int>();
    
                //Enqueing elements to the Queue
                Console.WriteLine("Enqueing elements to the Queue");
                for (int i = 0; i < 10; i++)
                {
                    testQueue.Enqueue(i);
                }
                Console.WriteLine("Enqueing of Elements to the Queue is finished");
    
                // Dequing elements from the Queue
                // Please note stack is FIFO (First In First Out), Hence 0 should be 
                // dequed first, then 1, then 2, nd so on ... 
    
                Console.WriteLine("Dequing elements from the Queue started");
    
                for (int i = 0; i < 10; i++)
                {
                    Console.WriteLine("Dequed element is : " + testQueue.Dequeue());
                }
                Console.WriteLine("Dequeing of Elements from the Queue is finished");
    
                // Waiting for enter to be pressed by user to prevent the Console Screen from 
                // closing automatically.
                Console.ReadLine();
    
            }
        }
    }
    
    
    Output: The output would look like this: 


    Hope you liked the article. Let us know your feedback through comments. Cheers!!

    Tuesday, December 15, 2015

    C# : Implementation of Stack using C#

    How to implement a Stack using C# 


    C# is pretty good at supporting various Data Structures and Stack is one of them. Let us first understand the concept of a stack.

    Definition

    According to Wikipedia,

    "In Computer Science a stack or LIFO (last in, first out) is an abstract data type that serves as a collection of elements, with two principal operations: push, which adds an element to the collection, and pop, which removes the last element that was added.

    The term LIFO stems from the fact that, using these operations, each element "popped off" a stack in series of pushes and pops is the last (most recent) element that was "pushed into" within the sequence."

    The following image illustrates the above concept:


    Image Source: wikipedia.org

    Simple representation of stack runtime with push and pop operations

    Applications of Stack

    There are many applications of stack. The most profound use that we mostly encounter is the Function Calls. For example, while executing the code we branch of from a certain instruction, the current instruction and related data is pushed on to the stack. Now the branched instruction and related data is also pushed on to stack. Once the branch instruction is executed, it is popped of the stack. Now we have the instruction from where we left or branched, on top of the stack. Hence Stack are very useful at certain places. Some of the applications are listed below:


    • Parsing
    • Recursive Functions
    • Calling Function
    • Expression Evaluation
    • Expression Conversion 
                1) Infix to Postfix
                2) Infix to Prefix
                3) Postfix to Infix
                4) Prefix to Infix
      • Towers of Hanoi, etc...
      Let us directly jump to the implementation of Stack using C#. Let us follow the following steps to implement the Stack. We are be using Visual Studio Professional 2015 for this.

      Step 1Open Visual Studio Professional 2015


      Step 2Click on New Project. Select Console Application and give desired Name to the application.


      Step 3Click on OK and you will get the following Screen



      Step 4: The overall implementation or the code should like the following.

      using System;
      using System.Collections.Generic;
      using System.Linq;
      using System.Text;
      using System.Threading.Tasks;
      
      namespace ConsoleStackExample
      {
          class Program
          {
              static void Main(string[] args)
              {
                  // Main Method
                  // In this example we will see basic implementation of 
                  // Data Structure: Stack using the language C#.
      
                  //Declaring a Stack of integers
                  Stack<int> testStack = new Stack<int>();
      
                  //Pushing elements on the stack
                  Console.WriteLine("Pushing Elements on the Stack");
                  for (int i = 0; i < 10; i++)
                  {
                      testStack.Push(i);
                  }
                  Console.WriteLine("Pushing of Elements on the Stack is finished");
      
                  // Popping elements of the stack
                  // Please note stack is LIFO (Last In First Out), Hence 9 should be 
                  // popped first,then 8, then 7, nd so on ... 
      
                  Console.WriteLine("Popping elements of the stack started");
      
                  for (int i = 0; i < 10; i++)
                  {
                      Console.WriteLine("Popped element is : " + testStack.Pop());
                  }
                  Console.WriteLine("Popping of Elements from the Stack is finished");
      
                  // Waiting for enter to be pressed by user to hold the 
                  //   Console Screen from closing automatically.
                  Console.ReadLine();
      
              }
          }
      } 


      OutputThe output would look like this:


      Hope you liked the article. Let us know your feedback through comments. Cheers!!