C# Algorithms Examples – Programming, Pseudocode Example, C# Programming Example

# C# Algorithms Examples

These C# examples cover a wide range of programming areas in Computer Science. Every example program includes the description of the program, C# code as well as output of the program. All examples are compiled and tested on Visual Studio.

# C# – Brute-Force Algorithm

In this example, we will learn C# implementation of Brute-Force Algorithm.Brute-force search or exhaustive search, also known as generate and test, is a very general problem-solving technique that consists of systematically enumerating all possible candidates for the solution and checking whether each candidate satisfies the problem’s statement.

True

# C# – Knapsack Problem

In this exapmles, we will write C# implementation for Knapsack problem

# C# – Bellman–Ford Algorithm

In this example, we will learn C# implementation of Bellman–Ford Algorithm for determining the shortest paths from a single source vertex to all of the other vertices in a weighted graph

### Output:

Vertex Distance from source
0 0
1 -1
2 2
3 -2
4 1

# C# – Floyd–Warshall Algorithm

In this article, we will learn C# implementation of Floyd–Warshall Algorithm for determining the shortest paths in a weighted graph with positive or negative edge weights

### Output:

Shortest distances between every pair of vertices:
0 6 10 11
cst 0 4 6
cst cst 0 2
cst cst cst 0

# C# – Dijkstra Algorithm for Determining the Shortest Path

### In this article, we will learn C# implementation of Dijkstra Algorithm for Determining the Shortest Path

Dijkstra’s algorithm is an algorithm for finding the shortest paths between nodes in a graph.It was conceived by computer scientist Edsger W. Dijkstra in 1956.This algorithm helps to find the shortest path from a point in a graph (the source) to a destination.

### Output:

Vertex Distance from source
0  0
1  6
2  15
3  20
4  22
5  12
6  10
7  9
8  14

# C# – Breadth First Search (BFS) using Queue

### In this example, we will write a C# program to implement Breadth First Search (BFS) using Queue

Breadth-first search (BFS) is an algorithm for traversing or searching tree or graph data structures. It starts at the tree root (or some arbitrary node of a graph) and explores the neighbor nodes first, before moving to the next level neighbors.

Traverse Graph:
——–
Eva
Sophia
Lisa
John
Brian
Tina
Mike

Search in Graph:
——-
Eva
Brian

# C# – Depth First Seach (DFS) using List

### In this example, we will write a C# program to implement Depth First Search using List.

Depth-first search (DFS) is an algorithm for traversing or searching tree or graph data structures. One starts at the root (selecting some arbitrary node as the root in the case of a graph) and explores as far as possible along each branch before backtracking.

Traverse Graph:
——–
Eva
Sophia
Lisa
John
Brian
Tina
Mike

Search in Graph:
——-
Eva
Brian

# C# – Huffman coding using Dictionary

### In this example, we will learn the C# implementation for Huffman coding using Dictionary.

Huffman coding is a lossless data compression algorithm. The idea is to assign variable-legth codes to input characters, lengths of the assigned codes are based on the frequencies of corresponding characters. The most frequent character gets the smallest code and the least frequent character gets the largest code.

### Output:

welcome to cce
Encoded: 01010101100100011101010101010010100101010100101010010101001010101011100101000111
Decoded: welcome to cce

# C# – Coin change problem : Greedy algorithm

### In this example, we will discuss an optimal solution to solve Coin change problem using Greedy algorithm.

A greedy algorithm is the one that always chooses the best solution at the time, with no regard for how that choice will affect future choices.Here, we will discuss how to use Greedy algorithm to making coin changes.

It has been proven that an optimal solution for coin changing can always be found using the current American denominations of coins

For an example, Let’s say you buy some items at the store and the change from your purchase is 63 cents. How does the clerk determine the change to give you? If the clerk follows a greedy algorithm, he or she gives you two quarters, a dime, and three pennies. That is the smallest number of coins that will equal 63 cents.

### Output:

Enter the amount you want to change : 0.63
The best way to change 0.63 cents is:
Number of quarters : 2
Number of dimes: 1
Number of pennies: 3

# C# – Hash data using salt

### Output:

Please enter the string for hashing: Welcome to cce
Original string: Welcome to cce
Hash values:
MD5 : SC4LSYSAkKILp2rPW1ZVpOP1WK7g
SHA1 : E0CfoAleTy9lDL8PmqLlY76jg3k/as3G5DPe
SHA256: p4OqMcDW33DzkGR7+UskcFv75yq/Jb7K49mRwRYHLdw0+HTwq3sS
SHA384: Tq6F1p1Hhan+tGPLOS+T6ltPh7wvTtPqgvgd4BKCTPEGnXCOEQpcrm0IELEjnobkWKY9
SHA512: UjtzgRAx4BWpMKYb1Qnrhn3Nlj84MrKNX1zJbNW33saM9IEtRmpzn4Ny6Y5oITg3TkSZ

# C# – Encrypt and Decrypt data using a symmetric key – Rijndael Algorithm

### What is Symmetric Key?

Symmetric-key algorithms are algorithms for cryptography that use the same cryptographic keys for both encryption of plaintext and decryption of ciphertext. The keys may be identical or there may be a simple transformation to go between the two keys.

### C# Implementation to Encrypt and Decrypt data using a symmetric key :

In below implementation, we will use Rijndael Algorithm to encrypt & decrypt data in C#. below are the few key parameters we will be using in C# implementation.
– passPhrase : Passphrase from which a pseudo-random password will be derived. The derived password will be used to generate the encryption key. Passphrase can be any string.
– saltValue : Salt value used along with passphrase to generate password. Salt can be any string.
– hashAlgorithm : Hash algorithm used to generate password. Allowed values are: “MD5” and “SHA256”
passwordIterations : Number of iterations used to generate password. One or two iterations should be enough.
– initVector : Initialization vector (or IV). This value is required to encrypt the first block of plaintext data. For RijndaelManaged class IV must be exactly 16 ASCII characters long.
– keySize : Size of encryption key in bits. Allowed values are: 128, 192, and 256.

### Output:

Input the Original Plain Text : welcome to cce!
Pliantext : welcome to csharpstar !
Encrypted : 1FJaiATQu8t5Mt23V+R1L1/Rj03JxYa18MSOHtpfYoA=
Decrypted : welcome to cce!

100
200
300
400
500
200
300
500

# Create a Circular Singly Linked List in C#

– In the circular linked list we can insert elements anywhere in the list
– In the circular linked list the previous element stores the address of the next element and the last element stores the address of the starting element.
– The circular linked list has a dynamic size and the memory can be allocated when it is required.

### Output:

Only one node…
Current Node Value : 100
Total Node: 5
Current Node Value : 300
Total Node: 5
Current Node Value : 500
Total Node: 5
Forward Direction…
100
200
300
400
500
Forward Direction…
200
300
400
500

# Towers of Hanoi in C#

### Towers of Hanoi or Tower of Brahma or Lucas’ Tower

Tower of Hanoi is a mathematical game or puzzle. It consists of three rods(towers), and a number of disks of different sizes which can slide onto any rod. The puzzle starts with the disks in a neat stack in ascending order of size on one rod, the smallest at the top, thus making a conical shape.

The objective of the puzzle is to move the entire stack to another rod, obeying the following simple rules:

• Only one disk can be moved at a time.
• Each move consists of taking the upper disk from one of the towers and placing it on top of another tower i.e. a disk can only be moved if it is the uppermost disk on a tower.
• No disk may be placed on top of a smaller disk.

### Output:

Move disk from A to C
Move disk from A to B
Move disk from C to B
Move disk from A to C
Move disk from B to A
Move disk from B to C
Move disk from A to C

# C# Program to Implement Stack with Push and Pop operations

### In this example, we will write a C# program to implement stack with Push and Pop Operations.

The primary operations you perform with a stack are Push and Pop. Data is added to a stack with the Push method. Data is removed from the stack with the Pop method.

### Output:

2. See the Top Element
3. Remove the Top Element
4. Display Stack Elements
5. Exit
Enter the Element : 12
Item Pushed Successfully!
Enter the Element : 45
Item Pushed Successfully!
Item 2 :45
Item 1 :12
Top element is : 45
Element removed : 45
Item 1 :12

# C# Program to Implement Stack

### In this article, we will write a C# program to Implement Stack with an example

The stack is one of the most frequently used data structures. We define a stack as a list of items that are accessible only from the end of the list, which is called the top of the stack. For an example, trays at a cafeteria.Trays are always removed from the top, and the when the dishwasher or busboy puts a tray back on the stack, it is placed on the top also. A stack is known as a Last-in, First-out (LIFO) data
structure.

In below example, we will write a C# program that uses Stack to identify if the string is palindromic.

### Output:

eye is a palindrome

# C# Program to Delete nodes from Binary Search Tree

• Removing a Leaf Node From a BST
• Deleting a Node With One Child
• Deleting a Node With Two Children

### Removing a Leaf Node From a BST:

Removing a leaf is the simplest case sincethere are no child nodes to take into consideration.All we have to do is set each child node of the target node’s parent to null. So, the node will still be there, but there will not be any references to the node.

– The while loop takes us to the node we are deleting.
– The first test is to see if the left child and the right child of that node are null.
– Then we test to see if this node is the root node. If so, we set it to null, otherwise, we either set the left node of the parent to null (if isLeftChild is true) or we set the right node of the parent to null.

# C# Program to Implement Binary Search Tree Traversal – Preorder,InOrder & Postorder

### Binary Search Tree Traversal:

You can learn how to implement Binary search Tree in C# and Insert nodes in BST here.

There are three traversal methods used with Binary Search Tree: inorder, preorder, and postorder.
– An inorder traversal visits all the nodes in a BST in ascending order of the node key values.
– A preorder traversal visits the root node first, followed by the nodes in the subtrees under the left child of the root, followed by the nodes in the subtrees under the right child of the root
– A postorder traversal, the method first recurses over the left subtrees and then over the right subtrees.

# C# program to find the most frequent element in an Array

### Using Hashtable:

You can use Hashtable, to find the most frequent element in an Array.