• Top Posts

    C# Console Interview Programs

    Linked List Implementation in C#:


    • Linked List is a linear data structure which stores element in the non-contiguous location. The elements in a linked list are linked with each other using pointers. Or in other words, Linked List consists of nodes where each node contains a data field and a reference(link) to the next node in the list.
    • In C#, Linked List is the generic type of collection which is defined in System.Collections.Generic namespace. It is a doubly linked list, therefore, each node points forward to the Next node and backward to the Previous node. It is a dynamic collection which grows, according to the need of your program.
     using System;  
     using System.Collections.Generic;  
     using System.Linq;  
     using System.Text;  
     using System.Threading.Tasks;  
     namespace Page  
     {  
       class Program  
       {  
         class ListNode  
         {  
           // automatic read-only property Data  
           public object Data { get; private set; }  
           // automatic property Next  
           public ListNode Next { get; set; }  
           public ListNode(object dataValue) : this(dataValue, null) { }  
           public ListNode(object dataValue, ListNode nextNode)  
           {  
             Data = dataValue;  
             Next = nextNode;  
           }  
           public class List  
           {  
             private ListNode firstNode;  
             private ListNode lastNode;  
             private string name; // string like "list" to display  
             public List(string listName)  
             {  
               name = listName;  
               firstNode = lastNode = null;  
             }  
             public List() : this("list") { }  
             public void InsertAtFront(object insertItem)  
             {  
               if (IsEmpty())  
               {  
                 firstNode = lastNode = new ListNode(insertItem);  
               }  
               else  
               {  
                 firstNode = new ListNode(insertItem, firstNode);  
               }  
             }  
             public void InsertAtBack(object insertItem)  
             {  
               if (IsEmpty())  
               {  
                 firstNode = lastNode = new ListNode(insertItem);  
               }  
               else  
               {  
                 lastNode = lastNode.Next = new ListNode(insertItem);  
               }  
             }  
             public object RemoveFromFront()  
             {  
               if (IsEmpty())  
               {  
                 throw new EmptyListException(name);  
               }  
               object removeItem = firstNode.Data; // retrieve data  
                                 // reset firstNode and lastNode references  
               if (firstNode == lastNode)  
               {  
                 firstNode = lastNode = null;  
               }  
               else  
               {  
                 firstNode = firstNode.Next;  
               }  
               return removeItem; // return removed data  
             }  
             public object RemoveFromBack()  
             {  
               if (IsEmpty())  
               {  
                 throw new EmptyListException(name);  
               }  
               object removeItem = lastNode.Data; // retrieve data  
                                 // reset firstNode and lastNode references  
               if (firstNode == lastNode)  
               {  
                 firstNode = lastNode = null;  
               }  
               else  
               {  
                 ListNode current = firstNode;  
                 // loop while current.Next is not lastNode  
                 while (current.Next != lastNode)  
                 {  
                   current = current.Next; // move to next node  
                 }  
                 // current is new lastNode  
                 lastNode = current;  
                 current.Next = null;  
               }  
               return removeItem; // return removed data  
             }  
             public bool IsEmpty()  
             {  
               return firstNode == null;  
             }  
             public void Display()  
             {  
               if (IsEmpty())  
               {  
                 Console.WriteLine($"Empty {name}");  
               }  
               else  
               {  
                 Console.Write($"The {name} is: ");  
                 ListNode current = firstNode;  
                 // output current node data while not at end of list  
                 while (current != null)  
                 {  
                   Console.Write($"{current.Data} ");  
                   current = current.Next;  
                 }  
                 Console.WriteLine("\n");  
               }  
             }  
           }  
           public class EmptyListException : Exception  
           {  
             public EmptyListException() : base("The list is empty") { }  
             public EmptyListException(string name) : base($"The {name} is empty") { }  
             public EmptyListException(string exception, Exception inner) : base(exception, inner) { }  
           }  
           class ListTest  
           {  
             static void Main()  
             {  
               var list = new List();  
               bool aBoolean = true;  
               char aCharacter = '$';  
               int anInteger = 3;  
               string aString = "hello";  
               list.InsertAtFront(aBoolean);  
               list.Display();  
               list.InsertAtFront(aCharacter);  
               list.Display();  
               list.InsertAtBack(anInteger);  
               list.Display();  
               list.InsertAtBack(aString);  
               list.Display();  
               // remove data from list and display after each removal  
               try  
               {  
                 object removedObject = list.RemoveFromFront();  
                 Console.WriteLine($"{removedObject} removed");  
                 list.Display();  
                 removedObject = list.RemoveFromFront();  
                 Console.WriteLine($"{removedObject} removed");  
                 list.Display();  
                 removedObject = list.RemoveFromBack();  
                 Console.WriteLine($"{removedObject} removed");  
                 list.Display();  
                 removedObject = list.RemoveFromBack();  
                 Console.WriteLine($"{removedObject} removed");  
                 list.Display();  
               }  
               catch (EmptyListException emptyListException)  
               {  
                 Console.Error.WriteLine($"\n{emptyListException}");  
               }  
               Console.ReadLine();  
             }  
           }  
         }  
       }  
     }  
    

    C# Progra to caluclate distance between Two Points:

     class DistanceofPoints  
       {  
         public static void Main()  
         {  
           Map myMap = new Map();  
           Location location1 = new Location();  
           Location location2 = new Location();  
           location1.setX(10);  
           location1.setY(10);  
           location2.setX(10);  
           location2.setY(20);  
           Console.WriteLine("Distance integers: " + myMap.Distance(5, 10, 5, 30));  
           Console.WriteLine("Distance doubles: " + myMap.Distance(15.4, 20.6, 15.4, 30.60));  
           Console.WriteLine("Distance location objects: " + myMap.Distance(location1, location2));  
           Console.ReadLine();  
         }  
       }  
       class Map  
       {  
         public double Distance(int x1, int y1, int x2, int y2)  
         {  
           Console.WriteLine("\nUsing the integer version");  
           return Math.Sqrt(Math.Pow(x1 - x2, 2) + Math.Pow(y1 - y2, 2));  
         }  
         public double Distance(double x1, double y1, double x2, double y2)  
         {  
           Console.WriteLine("\nUsing the double version");  
           return Math.Sqrt(Math.Pow(x1 - x2, 2) + Math.Pow(y1 - y2, 2));  
         }  
         public double Distance(Location L1, Location L2)  
         {  
           Console.WriteLine("\nUsing the Location objects version");  
           return Math.Sqrt(Math.Pow(L1.getX() - L2.getX(), 2) +  
           Math.Pow(L1.getY() - L2.getY(), 2));  
         }  
       }  
       class Location  
       {  
         private int x = 0;  
         private int y = 0;  
         public void setX(int newX)  
         {  
           x = newX;  
         }  
         public void setY(int newY)  
         {  
           y = newY;  
         }  
         public int getX()  
         {  
           return x;  
         }  
         public int getY()  
         {  
           return y;  
         }  
       }  
    


    Create a Queue by inheriting List's capabilities:


     using System;  
     using System.Collections.Generic;  
     using System.Linq;  
     using System.Text;  
     using System.Threading.Tasks;  
     namespace Page  
     {  
       public class MyQueue : List  
       {  
         // pass name "queue" to List constructor  
         public MyQueue() : base("queue") { }  
         // place dataValue at end of queue by inserting  
         // dataValue at end of linked list  
         public void Enqueue(object dataValue)  
         {  
           InsertAtBack(dataValue);  
         }  
         // remove item from front of queue by removing  
         // item at front of linked list  
         public object Dequeue()  
         {  
           return RemoveFromFront();  
         }  
       }  
       class Queue  
       {  
         static void Main()  
         {  
           MyQueue queue = new MyQueue();  
           // create objects to store in the queue  
           bool aBoolean = true;  
           char aCharacter = '$';  
           int anInteger = 34567;  
           string aString = "hello";  
           // use method Enqueue to add items to queue  
           queue.Enqueue(aBoolean);  
           queue.Display();  
           queue.Enqueue(aCharacter);  
           queue.Display();  
           queue.Enqueue(anInteger);  
           queue.Display();  
           queue.Enqueue(aString);  
           queue.Display();  
           // use method Dequeue to remove items from queue  
           object removedObject = null;  
           // remove items from queue  
           try  
           {  
             while (true)  
             {  
               removedObject = queue.Dequeue();  
               Console.WriteLine($"{removedObject} dequeued");  
               queue.Display();  
             }  
           }  
           catch (EmptyListException emptyListException)  
           {  
             // if exception occurs, write stack trace  
             Console.Error.WriteLine(emptyListException.StackTrace);  
           }  
           Console.ReadLine();  
         }  
       }  
       class ListNode  
       {  
         // automatic read-only property Data  
         public object Data { get; private set; }  
         // automatic property Next  
         public ListNode Next { get; set; }  
         public ListNode(object dataValue) : this(dataValue, null) { }  
         public ListNode(object dataValue, ListNode nextNode)  
         {  
           Data = dataValue;  
           Next = nextNode;  
         }  
       }  
       public class List  
       {  
         private ListNode firstNode;  
         private ListNode lastNode;  
         private string name; // string like "list" to display  
         public List(string listName)  
         {  
           name = listName;  
           firstNode = lastNode = null;  
         }  
         public List() : this("list") { }  
         public void InsertAtFront(object insertItem)  
         {  
           if (IsEmpty())  
           {  
             firstNode = lastNode = new ListNode(insertItem);  
           }  
           else  
           {  
             firstNode = new ListNode(insertItem, firstNode);  
           }  
         }  
         public void InsertAtBack(object insertItem)  
         {  
           if (IsEmpty())  
           {  
             firstNode = lastNode = new ListNode(insertItem);  
           }  
           else  
           {  
             lastNode = lastNode.Next = new ListNode(insertItem);  
           }  
         }  
         public object RemoveFromFront()  
         {  
           if (IsEmpty())  
           {  
             throw new EmptyListException(name);  
           }  
           object removeItem = firstNode.Data; // retrieve data  
                             // reset firstNode and lastNode references  
           if (firstNode == lastNode)  
           {  
             firstNode = lastNode = null;  
           }  
           else  
           {  
             firstNode = firstNode.Next;  
           }  
           return removeItem; // return removed data  
         }  
         public object RemoveFromBack()  
         {  
           if (IsEmpty())  
           {  
             throw new EmptyListException(name);  
           }  
           object removeItem = lastNode.Data; // retrieve data  
                             // reset firstNode and lastNode references  
           if (firstNode == lastNode)  
           {  
             firstNode = lastNode = null;  
           }  
           else  
           {  
             ListNode current = firstNode;  
             // loop while current.Next is not lastNode  
             while (current.Next != lastNode)  
             {  
               current = current.Next; // move to next node  
             }  
             // current is new lastNode  
             lastNode = current;  
             current.Next = null;  
           }  
           return removeItem; // return removed data  
         }  
         public bool IsEmpty()  
         {  
           return firstNode == null;  
         }  
         public void Display()  
         {  
           if (IsEmpty())  
           {  
             Console.WriteLine($"Empty {name}");  
           }  
           else  
           {  
             Console.Write($"The {name} is: ");  
             ListNode current = firstNode;  
             // output current node data while not at end of list  
             while (current != null)  
             {  
               Console.Write($"{current.Data} ");  
               current = current.Next;  
             }  
             Console.WriteLine("\n");  
           }  
         }  
       }  
       public class EmptyListException : Exception  
       {  
         public EmptyListException() : base("The list is empty") { }  
         public EmptyListException(string name)  
         : base($"The {name} is empty") { }  
         public EmptyListException(string exception, Exception inner)  
         : base(exception, inner) { }  
       }  
     }  
    
    

    Implementing a stack by inheriting from class List

     using System;  
     using System.Collections.Generic;  
     using System.Linq;  
     using System.Text;  
     using System.Threading.Tasks;  
     namespace Page  
     {  
       public class StackInheritance : List  
       {  
         // pass name "stack" to List constructor  
         public StackInheritance() : base("stack") { }  
         // place dataValue at top of stack by inserting dataValue at front of linked list  
         public void Push(object dataValue)  
         {  
           InsertAtFront(dataValue);  
         }  
         // remove item from top of stack by removing item at front of linked list  
         public object Pop()  
         {  
           return RemoveFromFront();  
         }  
       }  
       class Stack1  
       {  
         static void Main()  
         {  
           StackInheritance stack = new StackInheritance();  
           // create objects to store in the stack  
           bool aBoolean = true;  
           char aCharacter = '$';  
           int anInteger = 3;  
           string aString = "hello";  
           // use method Push to add items to stack  
           stack.Push(aBoolean);  
           stack.Display();  
           stack.Push(aCharacter);  
           stack.Display();  
           stack.Push(anInteger);  
           stack.Display();  
           stack.Push(aString);  
           stack.Display();  
           try  
           {  
             while (true)  
             {  
               object removedObject = stack.Pop();  
               Console.WriteLine($"{removedObject} popped");  
               stack.Display();  
             }  
           }  
           catch (EmptyListException emptyListException)  
           {  
             // if exception occurs, write stack trace  
             Console.Error.WriteLine(emptyListException.StackTrace);  
           }  
           Console.ReadLine();  
         }  
       }  
     }  
     class ListNode  
     {  
       // automatic read-only property Data  
       public object Data { get; private set; }  
       // automatic property Next  
       public ListNode Next { get; set; }  
       public ListNode(object dataValue) : this(dataValue, null) { }  
       public ListNode(object dataValue, ListNode nextNode)  
       {  
         Data = dataValue;  
         Next = nextNode;  
       }  
     }  
     public class List  
     {  
       private ListNode firstNode;  
       private ListNode lastNode;  
       private string name; // string like "list" to display  
       public List(string listName)  
       {  
         name = listName;  
         firstNode = lastNode = null;  
       }  
       public List() : this("list") { }  
       public void InsertAtFront(object insertItem)  
       {  
         if (IsEmpty())  
         {  
           firstNode = lastNode = new ListNode(insertItem);  
         }  
         else  
         {  
           firstNode = new ListNode(insertItem, firstNode);  
         }  
       }  
       public void InsertAtBack(object insertItem)  
       {  
         if (IsEmpty())  
         {  
           firstNode = lastNode = new ListNode(insertItem);  
         }  
         else  
         {  
           lastNode = lastNode.Next = new ListNode(insertItem);  
         }  
       }  
       public object RemoveFromFront()  
       {  
         if (IsEmpty())  
         {  
           throw new EmptyListException(name);  
         }  
         object removeItem = firstNode.Data; // retrieve data  
                           // reset firstNode and lastNode references  
         if (firstNode == lastNode)  
         {  
           firstNode = lastNode = null;  
         }  
         else  
         {  
           firstNode = firstNode.Next;  
         }  
         return removeItem; // return removed data  
       }  
       public object RemoveFromBack()  
       {  
         if (IsEmpty())  
         {  
           throw new EmptyListException(name);  
         }  
         object removeItem = lastNode.Data; // retrieve data  
                           // reset firstNode and lastNode references  
         if (firstNode == lastNode)  
         {  
           firstNode = lastNode = null;  
         }  
         else  
         {  
           ListNode current = firstNode;  
           // loop while current.Next is not lastNode  
           while (current.Next != lastNode)  
           {  
             current = current.Next; // move to next node  
           }  
           // current is new lastNode  
           lastNode = current;  
           current.Next = null;  
         }  
         return removeItem; // return removed data  
       }  
       public bool IsEmpty()  
       {  
         return firstNode == null;  
       }  
       public void Display()  
       {  
         if (IsEmpty())  
         {  
           Console.WriteLine($"Empty {name}");  
         }  
         else  
         {  
           Console.Write($"The {name} is: ");  
           ListNode current = firstNode;  
           // output current node data while not at end of list  
           while (current != null)  
           {  
             Console.Write($"{current.Data} ");  
             current = current.Next;  
           }  
           Console.WriteLine("\n");  
         }  
       }  
     }  
     public class EmptyListException : Exception  
     {  
       public EmptyListException() : base("The list is empty") { }  
       public EmptyListException(string name)  
       : base($"The {name} is empty") { }  
       public EmptyListException(string exception, Exception inner)  
       : base(exception, inner) { }  
     } 
    


    Create class Stack by encapsulating List's capabilities
     using System;  
     using System.Collections.Generic;  
     using System.Linq;  
     using System.Text;  
     using System.Threading.Tasks;  
     namespace Page  
     {  
       class MyStack  
       {  
         private List stack;  
         // construct empty stack  
         public MyStack()  
         {  
           stack = new List("stack");  
         }  
         // add object to stack  
         public void Push(object dataValue)  
         {  
           stack.InsertAtFront(dataValue);  
         }  
         // remove object from stack  
         public object Pop()  
         {  
           return stack.RemoveFromFront();  
         }  
         // determine whether stack is empty  
         public bool IsEmpty()  
         {  
           return stack.IsEmpty();  
         }  
         // output stack contents  
         public void Display()  
         {  
           stack.Display();  
         }  
         //public static void Main()  
         //{  
         //  Console.ReadLine();  
         //}  
       }  
       class ListNode1  
       {  
         // automatic read-only property Data  
         public object Data { get; private set; }  
         // automatic property Next  
         public ListNode Next { get; set; }  
         public ListNode1(object dataValue) : this(dataValue, null) { }  
         public ListNode1(object dataValue, ListNode nextNode)  
         {  
           Data = dataValue;  
           Next = nextNode;  
         }  
       }  
       public class List1  
       {  
         private ListNode firstNode;  
         private ListNode lastNode;  
         private string name; // string like "list" to display  
         public List1(string listName)  
         {  
           name = listName;  
           firstNode = lastNode = null;  
         }  
         public List1() : this("list") { }  
         public void InsertAtFront(object insertItem)  
         {  
           if (IsEmpty())  
           {  
             firstNode = lastNode = new ListNode(insertItem);  
           }  
           else  
           {  
             firstNode = new ListNode(insertItem, firstNode);  
           }  
         }  
         public void InsertAtBack(object insertItem)  
         {  
           if (IsEmpty())  
           {  
             firstNode = lastNode = new ListNode(insertItem);  
           }  
           else  
           {  
             lastNode = lastNode.Next = new ListNode(insertItem);  
           }  
         }  
         public object RemoveFromFront()  
         {  
           if (IsEmpty())  
           {  
             throw new EmptyListException(name);  
           }  
           object removeItem = firstNode.Data; // retrieve data  
                             // reset firstNode and lastNode references  
           if (firstNode == lastNode)  
           {  
             firstNode = lastNode = null;  
           }  
           else  
           {  
             firstNode = firstNode.Next;  
           }  
           return removeItem; // return removed data  
         }  
         public object RemoveFromBack()  
         {  
           if (IsEmpty())  
           {  
             throw new EmptyListException(name);  
           }  
           object removeItem = lastNode.Data; // retrieve data  
                             // reset firstNode and lastNode references  
           if (firstNode == lastNode)  
           {  
             firstNode = lastNode = null;  
           }  
           else  
           {  
             ListNode current = firstNode;  
             // loop while current.Next is not lastNode  
             while (current.Next != lastNode)  
             {  
               current = current.Next; // move to next node  
             }  
             // current is new lastNode  
             lastNode = current;  
             current.Next = null;  
           }  
           return removeItem; // return removed data  
         }  
         public bool IsEmpty()  
         {  
           return firstNode == null;  
         }  
         public void Display()  
         {  
           if (IsEmpty())  
           {  
             Console.WriteLine($"Empty {name}");  
           }  
           else  
           {  
             Console.Write($"The {name} is: ");  
             ListNode current = firstNode;  
             // output current node data while not at end of list  
             while (current != null)  
             {  
               Console.Write($"{current.Data} ");  
               current = current.Next;  
             }  
             Console.WriteLine("\n");  
           }  
         }  
       }  
     }  
    

    C# program to create generic Stack

     using System;  
     using System.Collections.Generic;  
     using System.Linq;  
     using System.Text;  
     using System.Threading.Tasks;  
     namespace Page  
     {  
       class EmptyStackException:Exception  
       {  
         public EmptyStackException() : base("Stack is empty")  
         {  
         }  
         // one-parameter constructor  
         public EmptyStackException(string exception) : base(exception)  
         {  
         }  
         // two-parameter constructor  
         public EmptyStackException(string exception, Exception inner)  
         : base(exception, inner)  
         {  
         }  
       }  
       public class FullStackException : Exception  
       {  
         // parameterless constructor  
         public FullStackException() : base("Stack is full")  
         {  
         }  
         // one-parameter constructor  
         public FullStackException(string exception) : base(exception)  
         {  
         }  
         // two-parameter constructor  
         public FullStackException(string exception, Exception inner)  
         : base(exception, inner)  
         {  
         }  
       }  
       public class Stack<T>  
       {  
         private int top; // location of the top element  
         private T[] elements; // array that stores stack elements  
                    // creates a stack of the default size  
         public Stack() : this(10) // default stack size  
         {  
         }  
         // creates a stack of the specified number of elements  
         public Stack(int stackSize)  
         {  
           if (stackSize <= 0) // validate stackSize  
           {  
             throw new ArgumentException("Stack size must be positive.");  
           }  
           elements = new T[stackSize]; // create stackSize elements  
           top = -1; // stack initially empty  
         }  
         // push element onto the stack; if unsuccessful, throw FullStackException  
         public void Push(T pushValue)  
         {  
           if (top == elements.Length - 1) // stack is full  
           {  
             throw new FullStackException(  
             $"Stack is full, cannot push {pushValue}");  
           }  
           ++top; // increment top  
           elements[top] = pushValue; // place pushValue on stack  
         }  
         // return the top element if not empty,  
         // else throw EmptyStackException  
         public T Pop()  
         {  
           if (top == -1) // stack is empty  
           {  
             throw new EmptyStackException("Stack is empty, cannot pop");  
           }  
           --top; // decrement top  
           return elements[top + 1]; // return top value  
         }  
       }  
       class StackTest  
       {  
         private static double[] doubleElements = { 1.1, 2.2, 3.3, 4.4, 5.5, 6.6 };  
         private static int[] intElements = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 };  
         private static Stack<double> doubleStack; // stack stores doubles  
         private static Stack<int> intStack; // stack stores ints  
         static void Main()  
         {  
           doubleStack = new Stack<double>(5); // stack of doubles  
           intStack = new Stack<int>(10); // stack of ints  
           TestPushDouble(); // push doubles onto doubleStack  
           TestPopDouble(); // pop doubles from doubleStack  
           TestPushInt(); // push ints onto intStack  
           TestPopInt(); // pop ints from intStack  
         }  
         private static void TestPushDouble()  
         {  
           try  
           {  
             Console.WriteLine("\nPushing elements onto doubleStack");  
             foreach (var element in doubleElements)  
             {  
               Console.Write($"{element:F1} ");  
               doubleStack.Push(element); // push onto doubleStack  
             }  
           }  
           catch (FullStackException exception)  
           {  
             Console.Error.WriteLine($"\nMessage: {exception.Message}");  
             Console.Error.WriteLine(exception.StackTrace);  
           }  
         }  
         private static void TestPopDouble()  
         {  
           try  
           {  
             Console.WriteLine("\nPopping elements from doubleStack");  
             double popValue; // store element removed from stack  
             while (true)  
             {  
               popValue = doubleStack.Pop(); // pop from doubleStack  
               Console.Write($"{popValue:F1} ");  
             }  
           }  
           catch (EmptyStackException exception)  
           {  
             Console.Error.WriteLine($"\nMessage: {exception.Message}");  
             Console.Error.WriteLine(exception.StackTrace);  
           }  
         }  
         private static void TestPushInt()  
         {  
           try  
           {  
             Console.WriteLine("\nPushing elements onto intStack");  
             foreach (var element in intElements)  
             {  
               Console.Write($"{element} ");  
               intStack.Push(element); // push onto intStack  
             }  
           }  
           catch (FullStackException exception)  
           {  
             Console.Error.WriteLine($"\nMessage: {exception.Message}");  
             Console.Error.WriteLine(exception.StackTrace);  
           }  
         }  
         private static void TestPopInt()  
         {  
           try  
           {  
             Console.WriteLine("\nPopping elements from intStack");  
             int popValue; // store element removed from stack  
             while (true)  
             {  
               popValue = intStack.Pop(); // pop from intStack  
               Console.Write($"{popValue:F1} ");  
             }  
           }  
           catch (EmptyStackException exception)  
           {  
             Console.Error.WriteLine($"\nMessage: {exception.Message}");  
             Console.Error.WriteLine(exception.StackTrace);  
           }  
         }  
       }  
     }  
    



    C# program to pass generic Stack as parameter

     using System;  
     using System.Collections.Generic;  
     using System.Linq;  
     using System.Text;  
     using System.Threading.Tasks;  
     namespace Stack_as_parameter  
     {  
       class Program:Exception  
       {  
         public Program() : base("Stack is empty")  
         {  
         }  
         // one-parameter constructor  
         public Program(string exception) : base(exception)  
         {  
         }  
         // two-parameter constructor  
         public Program(string exception, Exception inner)  
         : base(exception, inner)  
         {  
         }  
       }  
       public class FullStackException : Exception  
       {  
         // parameterless constructor  
         public FullStackException() : base("Stack is full")  
         {  
         }  
         // one-parameter constructor  
         public FullStackException(string exception) : base(exception)  
         {  
         }  
         // two-parameter constructor  
         public FullStackException(string exception, Exception inner)  
         : base(exception, inner)  
         {  
         }  
       }  
       public class Stack<T>  
       {  
         private int top; // location of the top element  
         private T[] elements; // array that stores stack elements  
                    // parameterless constructor creates a stack of the default size  
         public Stack()  
         : this(10) // default stack size  
         {  
         }  
         // constructor creates a stack of the specified number of elements  
         public Stack(int stackSize)  
         {  
           if (stackSize <= 0) // validate stackSize  
           {  
             throw new ArgumentException("Stack size must be positive.");  
           }  
           elements = new T[stackSize]; // create stackSize elements  
           top = -1; // stack initially empty  
         }  
         public void Push(T pushValue)  
         {  
           if (top == elements.Length - 1) // stack is full  
           {  
             throw new FullStackException(  
             $"Stack is full, cannot push {pushValue}");  
           }  
           ++top; // increment top  
           elements[top] = pushValue; // place pushValue on stack  
         }  
         // return the top element if not empty,  
         // else throw EmptyStackException  
         public T Pop()  
         {  
           if (top == -1) // stack is empty  
           {  
             throw new Program("Stack is empty, cannot pop");  
           }  
           --top; // decrement top  
           return elements[top + 1]; // return top value  
         }  
       }  
       class StackTest  
       {  
         // create arrays of doubles and ints  
         private static double[] doubleElements =  
         {1.1, 2.2, 3.3, 4.4, 5.5, 6.6};  
         private static int[] intElements =  
         {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11};  
         private static Stack<double> doubleStack; // stack stores doubles  
         private static Stack<int> intStack; // stack stores ints  
         static void Main()  
         {  
           doubleStack = new Stack<double>(5); // stack of doubles  
           intStack = new Stack<int>(10); // stack of ints  
           TestPush(nameof(doubleStack), doubleStack, doubleElements);  
           TestPop(nameof(doubleStack), doubleStack);  
           TestPush(nameof(doubleStack), intStack, intElements);  
           TestPop(nameof(doubleStack), intStack);  
         }  
         private static void TestPush<T>(string name, Stack<T> stack, IEnumerable<T> elements)  
         {  
           try  
           {  
             Console.WriteLine($"\nPushing elements onto {name}");  
             foreach (var element in elements)  
             {  
               Console.Write($"{element} ");  
               stack.Push(element); // push onto stack  
             }  
           }  
           catch (FullStackException exception)  
           {  
             Console.Error.WriteLine($"\nMessage: {exception.Message}");  
             Console.Error.WriteLine(exception.StackTrace);  
           }  
         }  
         private static void TestPop<T>(string name, Stack<T> stack)  
         {  
           try  
           {  
             Console.WriteLine($"\nPopping elements from {name}");  
             T popValue; // store element removed from stack  
             while (true)  
             {  
               popValue = stack.Pop(); // pop from stack  
               Console.Write($"{popValue} ");  
             }  
           }  
           catch (Program exception)  
           {  
             Console.Error.WriteLine($"\nMessage: {exception.Message}");  
             Console.Error.WriteLine(exception.StackTrace);  
           }  
           Console.ReadLine();  
         }  
       }  
     }  
    

    C# Program to create Binary Tree
     using System;  
     using System.Collections.Generic;  
     using System.Linq;  
     using System.Text;  
     using System.Threading.Tasks;  
     namespace BinaryTree  
     {  
       class Program  
       {  
         public Program LeftNode { get; set; }  
         public int Data { get; private set; }  
         public Program RightNode { get; set; }  
         public Program(int nodeData)  
         {  
           Data = nodeData;  
         }  
         // insert TreeNode into Tree that contains nodes;  
         // ignore duplicate values  
         public void Insert(int insertValue)  
         {  
           if (insertValue < Data) // insert in left subtree  
           {  
             // insert new TreeNode  
             if (LeftNode == null)  
             {  
               LeftNode = new Program(insertValue);  
             }  
             else // continue traversing left subtree  
             {  
               LeftNode.Insert(insertValue);  
             }  
           }  
           else if (insertValue > Data) // insert in right subtree  
           {  
             // insert new TreeNode  
             if (RightNode == null)  
             {  
               RightNode = new Program(insertValue);  
             }  
             else // continue traversing right subtree  
             {  
               RightNode.Insert(insertValue);  
             }  
           }  
         }  
       }  
       public class Tree  
       {  
         private Program root;  
         public void InsertNode(int insertValue)  
         {  
           if (root == null)  
           {  
             root = new Program(insertValue);  
           }  
           else  
           {  
             root.Insert(insertValue);  
           }  
         }  
         public void PreorderTraversal()  
         {  
           PreorderHelper(root);  
         }  
         private void PreorderHelper(Program node)  
         {  
           if (node != null)  
           {  
             Console.Write($"{node.Data} ");  
             PreorderHelper(node.LeftNode);  
             PreorderHelper(node.RightNode);  
           }  
         }  
         public void InorderTraversal()  
         {  
           InorderHelper(root);  
         }  
         private void InorderHelper(Program node)  
         {  
           if (node != null)  
           {  
             InorderHelper(node.LeftNode);  
             Console.Write($"{node.Data} ");  
             InorderHelper(node.RightNode);  
           }  
         }  
         public void PostorderTraversal()  
         {  
           PostorderHelper(root);  
         }  
         private void PostorderHelper(Program node)  
         {  
           if (node != null)  
           {  
             PostorderHelper(node.LeftNode);  
             PostorderHelper(node.RightNode);  
             Console.Write($"{node.Data} ");  
           }  
         }  
       }  
       class TreeTest  
       {  
         static void Main()  
         {  
           Tree tree = new Tree();  
           int insertValue;  
           Console.WriteLine("Inserting values: ");  
           Random random = new Random();  
           for (var i = 1; i <= 10; i++)  
           {  
             insertValue = random.Next(100);  
             Console.Write($"{insertValue} ");  
             tree.InsertNode(insertValue);  
           }  
           Console.WriteLine("\n\nPreorder traversal");  
           tree.PreorderTraversal();  
           Console.WriteLine("\n\nInorder traversal");  
           tree.InorderTraversal();  
           Console.WriteLine("\n\nPostorder traversal");  
           tree.PostorderTraversal();  
           Console.ReadLine();  
         }  
       }  
     } 
    


    C# program for Tree with IComparable objects

     using System;  
     using System.Collections.Generic;  
     using System.Linq;  
     using System.Text;  
     using System.Threading.Tasks;  
     namespace TreeWithIcom  
     {  
       class Program  
       {  
          // automatic property LeftNode  
         public Program LeftNode { get; set; }  
         public IComparable Data { get; private set; }  
         public Program RightNode { get; set; }  
         public Program(IComparable nodeData)  
         {  
           Data = nodeData;  
         }  
         public void Insert(IComparable insertValue)  
         {  
           if (insertValue.CompareTo(Data) < 0) // insert in left subtree  
           {  
             if (LeftNode == null)  
             {  
               LeftNode = new Program(insertValue);  
             }  
             else // continue traversing left subtree  
             {  
               LeftNode.Insert(insertValue);  
             }  
           }  
           else if (insertValue.CompareTo(Data) > 0) // insert in right  
           {  
             // insert new TreeNode  
             if (RightNode == null)  
             {  
               RightNode = new Program(insertValue);  
             }  
             else // continue traversing right subtree  
             {  
               RightNode.Insert(insertValue);  
             }  
           }  
         }  
       }  
       public class Tree  
       {  
         private Program root;  
         public void InsertNode(IComparable insertValue)  
         {  
           if (root == null)  
           {  
             root = new Program(insertValue);  
           }  
           else  
           {  
             root.Insert(insertValue);  
           }  
         }  
         public void PreorderTraversal()  
         {  
           PreorderHelper(root);  
         }  
         private void PreorderHelper(Program node)  
         {  
           if (node != null)  
           {  
             Console.Write($"{node.Data} ");  
             PreorderHelper(node.LeftNode);  
             PreorderHelper(node.RightNode);  
           }  
         }  
         public void InorderTraversal()  
         {  
           InorderHelper(root);  
         }  
         private void InorderHelper(Program node)  
         {  
           if (node != null)  
           {  
             InorderHelper(node.LeftNode);  
             Console.Write($"{node.Data} ");  
             InorderHelper(node.RightNode);  
           }  
         }  
         public void PostorderTraversal()  
         {  
           PostorderHelper(root);  
         }  
         private void PostorderHelper(Program node)  
         {  
           if (node != null)  
           {  
             PostorderHelper(node.LeftNode);  
             PostorderHelper(node.RightNode);  
             Console.Write($"{node.Data} ");  
           }  
         }  
       }  
       class TreeTeste  
       {  
         static void Main()  
         {  
           int[] intArray = { 8, 21, 24, 23, 31, 17, 25, 64 };  
           double[] doubleArray = { 8.8, 2.2, 4.4, 3.3, 1.1, 7.7, 5.5, 6.6 };  
           string[] stringArray = { "eight", "two", "four", "three", "one", "seven", "five", "six" };  
           // int Tree  
           Tree intTree = new Tree();  
           PopulateTree(intArray, intTree, nameof(intTree));  
           TraverseTree(intTree, nameof(intTree));  
           // double Tree  
           Tree doubleTree = new Tree();  
           PopulateTree(doubleArray, doubleTree, nameof(doubleTree));  
           TraverseTree(doubleTree, nameof(doubleTree));  
           // string Tree  
           Tree stringTree = new Tree();  
           PopulateTree(stringArray, stringTree, nameof(stringTree));  
           TraverseTree(stringTree, nameof(stringTree));  
           Console.ReadLine();  
         }  
         private static void PopulateTree(Array array, Tree tree, string name)  
         {  
           Console.WriteLine($"\n\n\nInserting into {name}:");  
           foreach (IComparable data in array)  
           {  
             Console.Write($"{data} ");  
             tree.InsertNode(data);  
           }  
         }  
         private static void TraverseTree(Tree tree, string treeType)  
         {  
           // perform preorder traversal of tree  
           Console.WriteLine($"\n\nPreorder traversal of {treeType}");  
           tree.PreorderTraversal();  
           // perform inorder traversal of tree  
           Console.WriteLine($"\n\nInorder traversal of {treeType}");  
           tree.InorderTraversal();  
           // perform postorder traversal of tree  
           Console.WriteLine($"\n\nPostorder traversal of {treeType}");  
           tree.PostorderTraversal();  
         }  
       }  
     }  
    


    Algorithm

    C# program to prints all possible cards from a standard deck of 52 cards

     using System;  
     using System.Collections.Generic;  
     using System.Linq;  
     using System.Text;  
     using System.Threading.Tasks;  
     namespace Algarithm  
     {  
       class Program  
       {  
         static void Main(string[] args)  
         {  
           string[] suit = { "spades", "hearts", "diamonds", "clubs" };  
           for (int i = 1; i <= 13; i++)//Karti  
           {  
             for (int j = 0; j < 4; j++)//Boq  
             {  
               switch (i)  
               {  
                 case 1:  
                   Console.WriteLine("Two of {0}", suit[j]);  
                   break;  
                 case 2:  
                   Console.WriteLine("Three of {0}", suit[j]);  
                   break;  
                 case 3:  
                   Console.WriteLine("Four of {0}", suit[j]);  
                   break;  
                 case 4:  
                   Console.WriteLine("Five of {0}", suit[j]);  
                   break;  
                 case 5:  
                   Console.WriteLine("Six of {0}", suit[j]);  
                   break;  
                 case 6:  
                   Console.WriteLine("Seven of {0}", suit[j]);  
                   break;  
                 case 7:  
                   Console.WriteLine("Eight of {0}", suit[j]);  
                   break;  
                 case 8:  
                   Console.WriteLine("Nine of {0}", suit[j]);  
                   break;  
                 case 9:  
                   Console.WriteLine("Ten of {0}", suit[j]);  
                   break;  
                 case 10:  
                   Console.WriteLine("Jack of {0}", suit[j]);  
                   break;  
                 case 11:  
                   Console.WriteLine("Queen of {0}", suit[j]);  
                   break;  
                 case 12:  
                   Console.WriteLine("King of {0}", suit[j]);  
                   break;  
                 case 13:  
                   Console.WriteLine("Ace of {0}", suit[j]);  
                   break;  
                 default:  
                   Console.WriteLine("Someting went wrong");  
                   break;  
               }  
             }  
             Console.ReadLine();  
           }  
         }  
       }  
     }  
    


    C# program to calculate the Nth Catalan number by given N

     class CatalanFormula  
       {  
         static void Main()  
         {  
           int n;  
           do  
           {  
             n = int.Parse(Console.ReadLine());  
           } while (n < 0);  
           int n2Fact = 1;  
           int n2Plus1Fact = 1;  
           int Nfact = 1;  
           for (int i = 1; i <= n; i++)  
           {  
             Nfact *= i;  
           }  
           for (int k = 1; k <= 2 * n; k++)  
           {  
             n2Fact *= k;  
           }  
           for (int j = 1; j <= n + 1; j++)  
           {  
             n2Plus1Fact *= j;  
           }  
           Console.WriteLine(n2Fact / (n2Plus1Fact * Nfact));  
           Console.ReadLine();  
         }  
       }  
    


    C# program to Calculates the greatest common divisor (GCD) of given two numbers. Use the Euclidean algorithm

      class GCD  
       {  
         static void Main()  
         {  
           int num1 = int.Parse(Console.ReadLine());  
           int num2 = int.Parse(Console.ReadLine());  
           while (num1 != 0 && num2 != 0)  
           {  
             if (num1 > num2)  
             {  
               num1 -= num2;  
             }  
             else  
             {  
               num2 -= num1;  
             }  
           }  
           Console.WriteLine(Math.Max(num1, num2));  
         }  
       }  
    

    C# program to calculates the sum of the first N members of the sequence of Fibonacci: 0, 1, 1, 2, 3, 5, 8, 13, 21
     using System;  
     using System.Collections.Generic;  
     using System.Linq;  
     using System.Text;  
     using System.Threading.Tasks;  
     namespace Algarithm  
     {  
       class Fibonacci  
       {  
         static void Main()  
         {  
           int n = int.Parse(Console.ReadLine());  
           Int64 temp = 0;  
           Int64 firstNum = 0;  
           Int64 secondNum = 1;  
           Int64 sum = 0;  
           if (n == 0 || n == 1)  
           {  
             Console.WriteLine(0);  
           }  
           else  
           {  
             for (int i = 0; i < (n - 2); i++)  
             {  
               temp = firstNum + secondNum;   
               firstNum = secondNum;  
               secondNum = temp;  
               sum += temp;  
             }  
             Console.WriteLine(1 + sum);  
           }  
         }  
       }  
     }  

    No comments

    Post Top Ad

    ad728

    Post Bottom Ad

    ad728