C# Algorithms Examples – C# Programming Example
Basic C# C# Console Pseudocode Examples

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.

Output:

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.

Output:

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

Search in Graph:
——-
Eva
Brian
Emplyee not found

 

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.

 

Output:

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

Search in Graph:
——-
Eva
Brian
Emplyee not found

 

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.

Node.cs :

HuffmanTree.cs :

Program to test Huffman Coding:

Output:

Please enter the string:
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.

C# Implementation on Coin change Problem using Greedy algorithm :

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

In this example, we will write a C# program to hash data/password using salt value

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

In this example, we will write a C# program to Encrypt and Decrypt data using a symmetric key

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!

 

C# Program to Implement Traversal in Singly Linked List

In this example, we will write a C# program to implement Singly LinkedList traversal

Output:

Traversing Singly Linked List :
100
200
300
400
500
Deleting from Linked List…
Traversing Singly Linked List :
200
300
500

Create a Circular Singly Linked List in C#

Circular Linked List is a linked data structure.
– 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.

Implementation of Singly Linked Circular List in C# :

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.

Solving Towers of Hanoi using Recursion:

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:

Stack MENU(size — 10)
1. Add an element
2. See the Top Element
3. Remove the Top Element
4. Display Stack Elements
5. Exit
Select your Choice : 1
Enter the Element : 12
Item Pushed Successfully!
Select your choice :1
Enter the Element : 45
Item Pushed Successfully!
Select your choice : 4
Item 2 :45
Item 1 :12
Select your choice : 2
Top element is : 45
Select your choice : 3
Element removed : 45
Select your choice : 4
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

 

In this article, we will learn:

  • 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

In this article, we will learn : Binary Search Tree Traversal in C#

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

In this example, we will learn different ways to find the most frequent element in an Array in C#.

Using Hashtable:

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

Output:

8,1
7,3
6,3
5,4
4,3
3,5
2,1
The common number is 3 and it appears 5 times

HashTable is not generic, which means it will box every int to an object.So you can se a Dictionary<int, int=””> instead.</int,>

 

C# program to check for Matching Parentheses

In this article, the problem statement is to write a java program that can check and if a string has matching pair of parentheses or not.

For example,

() has matching parenthesis, but (() doesn’t.

For this, we can maintain a counter for the opening parentheses encountered.

When you find an opening parenthesis, add 1 to the counter. Similarly, when you find a closing parenthesis, reduce 1 from the counter. In the end, if the counter is 0, then the parentheses are properly nested.

 

Output:

is false
is false
is false

is false
is false
is false

( is false
( is false
( is false

())))))) is false
())))))) is false
())))))) is false

(()((fff))()) is true
(()((fff))()) is true
(()((fff))()) is true

(() is false
(() is false
(() is false

()()()()()()()()()()()() is true
()()()()()()()()()()()() is true
()()()()()()()()()()()() is true

 

C# – String Distance (Hamming Distance,Levenshtein Distance & Damerau-Levenshtein

Distance) Algorithm

 

In this article, we will discuss:

  • Hamming Distance Algorithm
  • Levenshtein Distance Algorithm
  • Damerau-Levenshtein Distance Algorithm

1. Hamming Distance Algorithm:

The Hamming Distance measures the minimum number of substitutions required to change one string into the other.The Hamming distance between two strings of equal length is the number of positions at which the corresponding symbols are different.The Hamming distance is named after Richard Hamming.

In below example, we will take two strings and if length of strings are not equal then we will show exception else it will calculate the distance between two strings.

 

Output:

3
1
1

 

2. Levenshtein Distance Algorithm:

The Levenshtein distance is a string metric for measuring the difference between two sequences. The Levenshtein distance between two words is the minimum number of single-character edits (i.e. insertions, deletions or substitutions) required to change one word into the other. It is named after Vladimir Levenshtein.

Output:

3
2
2

 

Heap sort program in C#

In this example, we will discuss on Heap sort algorithm in C#

it divides its input into a sorted and an unsorted region, and it iteratively shrinks the unsorted region by extracting the largest element and moving that to the sorted region

It first removes the topmost item (the largest) and replace it with the rightmost leaf. The topmost item is stored in an array and Re-establish the heap.this is done until there are no more items left in the heap.

Here is the output of the C# Program:

Elements Before Sorting :
2
5
1
10
6
9
3
7
4
8
Elements After Sorting :
1
2
3
4
5
6
7
8
9
10

 

Comb sort program in C#

In this example, we will discuss on Comb sort algorithm in C#

Comb sort is sorting algorithm and it is a variant of Bubble sort, the Comb Sort increases the gap used in comparisons and exchanges.

Comb sort improves on bubble sort.

The basic idea is to eliminate turtles, or small values near the end of the list, since in a bubble sort these slow the sorting down tremendously

 

Output

-119
-58
-10
0
85
250
785

 

Merge sort program in C

In this article, we will discuss Merge sort in C#

Merge Sort is one of the popular sorting algorithms in C# as it uses the minimum number of comparisons.

The idea behind merge sort is that it is merging two sorted lists.

Merge sort is of order O(nlogn)

Here is a high-level representation of the Merge sort algorithm :

Here is in C#:

 

Output:

MergeSort By Recursive Method
1
2
3
4
5
6
7
8
9

 

Shell sort program in C#

In this article, we will write the Shell sort program in C#

Donald Shell published the first version of this sort, hence this is known as Shell sort.

This sorting is a generalization of insertion sort that allows the exchange of items that are far apart

It starts by comparing elements that are far apart and gradually reduces the gap between elements being compared.

The running time of Shell sort varies depending on the gap sequence it uses to sort the elements.

Output:

183 297 464

 

C# Program to Find whether the Number is Divisible by 2

In this example, we will write a C# program to find whether the number is divisible by 2 or not

Any whole number that ends in 0, 2, 4, 6, or 8 will be divisible by 2.Here the divisibility test is done by performing the mod function with 2.

Here is the output of the C# Program:

Enter the Number :
57
Entered Number is Not Divisible by 2

 

C# Program to Display the Factors of the Entered Number

In this example, we will write a C# program to generate factors for a given number.

The factors of a number are all those numbers that can divide evenly into the number with no remainder.

Here is the output of the C# Program:

Enter the Number : 27
The Factors are :
1
3
9
27

 

3 Different ways to calculate factorial in C#

1. Using For Loop: