## Minimal Spanning Trees and Kruskal’s Algorithm

Given a weighted graph G, it is often desired to generate a spanning tree such that the sum of the weights of the tree edges is a minimum. Such a tree is called a Minimum Spanning Tree. Such a method is the cheapest way of connecting all nodes of G. Kurskal’s Algorithm Kurskal’s algorithm is a…

## Depth First and Breadth First Traversal

Depth first traversal of a Graph could be used to traverse a directed or un-directed graph and thus creating a spanning tree. Depth first traversal is a pre-order traversal of the given graph or spanning tree. The traversal starts from a node and traverses along the path until it reaches a node which has no…

## Graph Traversals and Spanning Forests

Connected Graph A graph is said to be connected if there is a path between any two of its nodes. Cycle A Path from a node to itself is called a Cycle. A rgaph must require at least 3 nodes to form a cycle. Tree A Tree is a connected graph without cycles. Spanning Forests A…

## Linked representation of Graphs in C

There are many in-inadequacies in using the Adjacency Matrix representation of Graphs. Once such inadequacy is the difficulty in adding or deleting nodes while data is to be updated dynamically. Another inadequacy is that even if there exists no arc between two nodes, space must be reserved for the same in the array. Such inadequacies…

## Implementing Ford Fulkerson’s Algorithm in C To Maximize Network Flow

Flow Problem The main objective of a flow problem is to maximize the amount of an item being delivered from one point of a system to another. If we consider a water pipe system as shown below, our objective would be to maximize the amount of water flowing from source S to sink T. The…

## Implementation of Warshal’s Algorithm in C to find Path Matrices of a Graph

Warshal’s Algorithm can be applied to find the Path Matrices and this the TRANSITIVE CLOSURE of a graph given its adj matrix. Warshal’s algorithm is based on the fact that the Pathk+1[i][j] is TRUE if and only if any one of the following conditions is true – 1) Pathk[i][j] == TRUE 2) Pathk[i][k+1] == TRUE…

## Representing Graphs and Networks in C

A Graph is a data structure that consists of a set of nodes interconnected by directed or un-directed arcs. For a DIRECTED Graph, the ordered pair of nodes are written within angled brackets while for a UN-DIRECTED Graph, they are written within parenthesis. Consider a directed graph as depicted below – Below are the main point to note about the above…

Merge Sort Merge Sort is a process of combining more than one sorted files into a single sorted file. The procedure is to divide a file of size n into n sub files of size 1 each. Now combine each adjacent sub files to form a set of n/2 sub files. Sort each sub files….

## Insertion Sort and its implementation in C

Insertion Sort is a simple implementation of the general straight selection sort. A simple routine for insertion sort can be written as below – void insertionsort(int x[], int n){ int i, k, y; /*It is assumed that X is already sorted*/ for(k = 1; k < n; k++){ y = x[k]; for(i = k-1; i> =0…

## Heap Tree Sort and its implementation in C

Heap is an almost complete Binary Tree implemented in a sequential format such that the value at any of the nodes (nd) is >= or <= value of the children. If nd >= children –> Maxheap ; If nd <= children –> Minheap ; Inserting an item to a Heap Join the item at the end of…

## Binary Tree Sort in C

Binary Tree Sort uses a Binary search tree. The various steps involved in such a sort would be – Construct a binary tree with the given data (integers) such that all numbers to the left of a particular node say ‘nd’ is less than the number contained within the node and to the right, the numbers…

## Selection Sort

A Selection sorting technique uses a general algorithm which uses an ascending or descending priority queue. The idea would be to pre-process input array X[i] into the descending or ascending priority queues by the functions dpqinsert(dpq, x) or apqinsert(apq, x) respectively. Now, the next and final step would be to select data in appropriate order from…

## Bubble Sort in C

Lets explain Bubble sort by illustrating tow specific examples involving steps where smaller numbers bubbles to first and when larger numbers bubbles to last. Number list to sort: 2   5   3   0   6   1 Case 1: Smaller numbers bubbles to first Step 1:    0  5  3  2  6  1 Step 2:   0  3  5  2 …

## Efficiency and Order of a Sorting Program

Efficiency Considerations The following are the efficiency considerations while planning for a sorting program / algorithm – Time required to code the program and the type of sorting technique to be selected Execution time Amount of space required by program In cases where the type of data to be sorted is known, it is easier…

## Recursive C program for Towers of Hanoi

Towers of Hanoi problem consists of 3 pegs A, B and C. Let n denote number of disks in peg A. The objective is to transfer these disks from A to C using B as auxiliary so that at a time only one disk is transferred and a larger one cannot reside on a smaller…

## Efficiency of Recursion

In general cases, a non-recursive program runs more efficiently than a recursive program since a recursive program requires more execution time to enter and exit from a function. Recursive programs flows directly from the definitions and are easy to implement while a corresponding non-recursive program may involve expensive use of stacks which are difficult to…

## Recursion in C

Recursion Recursion and Iteration are two different concepts of achieving a result by a number of repeated operations. Iteration involves use of for, while and do-while loops for the repeated operation until specified condition. Recursion involves a recursive function calling itself several times until specified condition. A recursive function represents the most simpler form of…

Doubly Linked lists eliminates below drawbacks of circular lists – not able to traverse backward not able to delete and node given only points to that node. In a doubly linked list, every node has three fields – left, right and info. Each node has two pointers left and right which points to the left…

## Simulation of Josephus Problem using Circular lists

Josephus Problem Josephus problem is that some soldiers are being surrounded by their enemies and there is only one horse to escape i.e. only one soldier could escape and summon help. The remedy is to arrange soldiers’ names as a circular list. Now, any number say ‘n’ is inputed (selected) where n < number of…

## Dynamic Circular Linked Lists in C

Circular lists eliminates same drawbacks of linear lists. In as circular list it is assumed that items are inserted at the front and the list pointer points to the currently inserted node. Now, in this currently inserted circular list items, node or item is the last node of the list (and is this the rear…

## Advantages of Dynamic representation of Lists over its Array implementation

Below are the advantages of Dynamic representation of Lists over its Array implementation –  No advanced knowledge of number of nodes is required  No memory space is wasted by bulk allocation as in the case of a large array since memory space is allocated only when a node is created  A reference to a pointer…

## Dynamic Linked Lists as Queues in C

When Dynamic Linked Lists are represented as Queues, the first node represents front of queue given by q.front and last node represents the rear of the queue given by q.rear where q.front and q.rear are pointers. Thus Qinsert(q,x) and Qdelete(q) could be implemented as below – Qinsert(q,x){ p = getnode(); info(p) = x; next(p) =…

## Implementing Dynamic Linked Lists in C

List is a type of dynamic data structure which rectifies certain drawbacks of Stacks and Queues. Lists generally uses the concept of pointers which points to a memory location containing data. The basic structure of a linear linked list is a as follows –   Each item in a list is called NODE. Each NODE…

## Queues and its implementation in C

A Queue is a First In First Out (FIFO) which is an ordered collection of items which are deleted at the front end and inserted at the rear end. A simple queue is represented as below –         Simple Sequential Queue A Queue in C may be defined as an array as…

## Game Trees

Game Tree is one of the applications of Binary Trees. For example the one implemented for the Tic-Tac-Toe Game. X | X | X O | O |     O |   | The game is between two players who makes moves ‘X’ and ‘O’ on a board of 3×3 positions. The players who wins is…

## Representing Lists As Binary Trees in C

Case 1: A list could be represented as a Binary Tree with all the list elements along with their information at the leaf nodes. For example, the linked list ->[A| ]->[B| ]->[C| ]-> ………[I| ] could be represented as following Binary Tree – 5 / \ 2 2 / \ / \ 1 2 1…

## HUFFMAN Algorithm and its implementation in C

Huffman trees are used as message encoding and message decoding trees which is the basic construct of compression and de. The specialty of Huffman tree is that – it helps to reduce the bit codes of each symbol in the message according to their relative frequency of occurrence. the same tree constructed could be used for…

## Threaded Binary Tree and its implementation in C

Threaded Binary Trees are those in which the NULL right pointers of all nodes are THREADED to its immediate inorder successor in the Binary Tree. Such pointers or THREADS are also called RIGHT IN threads as they are always threaded to right. Example Structure of a Threaded Binary Tree A / \ B C / \…

## Traversing a Binary Tree in C

There are generally 3 traversal strategies for Binary Trees – INORDER, PREORDER and POSTORDER. For eg:, the inorder, preorder and postorder traversal of an expression tree gives the infix, prefix and postfix forms of the expression. Such a traversal could be used to evaluate the value of expression. Example 1 : Consider the following Binary Tree –…

## C program implementing Binary Tree Search to find duplicates of a file

A Binary Search is such a Binary Tree in which the info field of any of the nodes to the left of a particular node nd will be < that of nd and of those to the right of nd will be >= nd. The in-order traversal of such a tree will give the sorted form…

## Binary Tree representation and Primitive Operations on a Binary Tree in C

Binary Trees are one of the core data structures used in any programming language to implement complex systems. C programming language offers various binary tree operations that could be used by the developer. Binary Trees can be dynamically represented in C as shown below – struct nodetype{ int info; struct nodetype * left; struct nodetype * right;…

## C program to print sum up-to each individual preceding number until the entered number

Here is a C program which accepts an integer and prints out sum from 1 to 1, 1 to 2, 1 to 3 …… 1 up-to that number – main(){ int n,i,s=0; printf(“\nEnter any integer>>”); scanf(“%d”,&n); for(i = 1; i

## C program for Hailstones series

Hailstones is a sequence of numbers that could be generated from any positive number by performing a specific operation on it until it reaches 1. The fact is that any positive number will reach 1 if we perform this operation. If the number is even, we divide it by 2, otherwise we multiply the number…

## C program to generate random numbers in any range

Here is a C program to generate random numbers between any range of two digit numbers – #include #include main(){ int s, a, b, n, ran; srand(time(0)); // this is to set the seed to current time so we get different random numbers in each try printf(“\nEnter lower limit>>”); scanf(“%d”,&a); printf(“\nEnter upper limit>>”); scanf(“%d”,&b); printf(“\nEnter…

## for loops in C

The ‘for’  loop is another important looping structure which could replace ‘while’  and ‘do .. while’ loops. It has a special feature that the initialization, test condition and the increment or decrements of test variable could be placed in a single line following the ‘for’ keyword as shown below – for (initialization; test condition; change…

## C program to test for a prime number

Below is a C program to test for a prime number – main(){ float n, count = 0; i = 3; a; printf(“\nEnter any number of your choice>>”); scanf(“%f”, &n); if(n == 0 || n == 1 || n == 2) printf(“\n%d is not a prime number\n”, n); while(i > 2 & i < n){...

## C program to implement Russian Peasant

Here is a C program that I wrote years back to implement Russian Peasant method of an interesting multiplication technique – main(){ int a, b, sum = 0; printf(“\nEnter the two digits to be multiplied separated by space>> “); scanf(“%d %d”, &a, &b); printf(“%d “,a); printf(” %d\n”,b); do{ if(a % 2) sum += b; else…

## C program to find numbers whose sum of cubes of individual numbers is that number

Here is an implementation of while loop in C to find numbers whose sum of cubes of individual numbers is that number. You can go a step further and make it so that you accept value of i and n. main(){ int i = 1, a, b, c, n = 1000; printf(“\n Enter a number…

## C program to find circumference and area of a circle from given radius

Here is a simple C program to find circumference and area of a circle from given radius – main(){ float r, pi = 3.1416, c, area; printf(“\nEnter value of radius>> “); scanf(“%f”, &r); while (r > = 0.0){ c = 2*pi*r; area = pi*r*; printf(“\nCircumference = %f”, c); printf(“\nArea = %f”, area); scanf(“%f”, &r) } }

## While Loop in C

Like do-while loop, While loop is the most commonly used looping construct to repeat a process or calculation for a set or collection of inputs or storage based on a condition. It is a looping technique when you want to execute the required process based on a condition for the entire input collection. Below is…

## C program to find the sum of squares of first n natural numbers

Here is a simple C program to find the sum of squares of first n natural numbers using do-while looping construct – main(){ int n, sum =0; printf(“\nInput any integer of your choice>>”); scanf(“%d”,&n); nsave = n; do{ sum += n*n; n–; } while(n > 0); printf(“Sum of squares upto %d = %d \n”, nsave,…

## Do – While Loops in C

Looping constructs is an important programming language technique to repeat a process or calculation for a set or collection of inputs or storage based on a condition. Do – While is a looping technique when you want to execute the required process for at least once and then check the condition for the rest of the…

## Sample C program showing if – else constructs

Below are simple C programs for beginners to learn if-else decision construct. Example 1: Program to check if a number is odd or even main (){ int n; printf(“Please enter any number>> “); scanf(“%d”, &n); if(n % 2 == 0) printf(“\n%d is EVEN \n”, n); else printf(“\n%d is ODD \n”, n); } Example 2: Program…

## C Program to check for leap year

Here is a C program to check for leap year – main () { int year; printf(“Please enter any year as 4 digits>> “); scanf(“%d”, &year); if(year % 4 ==0 && year % 100 !=0 || year % 400 == 0) printf(“%d is a leap year \n”, year); else printf(“%d is not a leap year…

## Making decision in C program

Decision making is an important aspect of programming language that enables the programmer to arrive at a conclusion based on certain data processing, comparisons and conditional situations. In most programming language there are inbuilt functions and language constructs that enable implicit decision making. In other situations, it offers a combination of language constructs such as comparison…

## Declaring variables in C language

C programming language allows to define and classify data so we can use it appropriately in various parts of the program in the correct form with or without changing the original value or just copying the original value. Any data that we need to use in the program need to be stored in the memory….

## C Programming Language

C language developed at Bell lab by Dennis Ritchie on UNIX environment. UNIX was later rewritten in C. An earlier version of C is BCPL (Basic Combined Programming Language) developed by Ken Thompson. When it was later improvised by Dennis, it became C (‘C’ from BCPL) programming language. C program could be written either in…

## Recursive C program for Binary search

Below is an example Recursive C program to perform Binary – int binsearch(int low, int high, in a[], X){ int mid; if(low > high){ return(-1); } mid = (low + high) / 2; return(X == a[mid] ? mid : X < a [mid] ? binsearch(low, mid-1, a[], X) : binsearch (mid+1,high,a[],X)) }

## Recursive C program to print Fibonacci series

Below is an example recursive C program to return Fibonacci series for a given number – int fibonacci (int x){ if(n < 0){ printf("Invalid input"); exit(1); } else{ return ((n==1 || n==1)? n : fib(n-2) + fib(n-1)); } }

## C program for finding factorial by recursion

Here is a C program to find a factorial by recursive method – int factorial (int x ) { return ( n==0? 1: n*(fact(n-1))); }

## Bubble sort in C

Simple bubble sort in C – for (i=0; i<n-1; i++){ for(j=i+1; j<n; j++){ if(x[j] < x[i]){ temp = x[j]; x[j] = x[i]; x[i] = temp; } } }

## Tree representation in C

Below is an example to represent a Tree structure in C using struct

## File Operation in C

Below is a simple C program to perform file operation – include <stdlib.h> main() { FILE * file_source char * file_name = (char*) malloc (sizeof (char)* 13); char * file_content= (char*) malloc (sizeof (char)* 100); printf(“Enter File Name>”); gets (file_name); file_source = fopen(file_name, “r+”); if(file_source == NULL) { printf(“File doesn’t exist”); } else{ while (…

## C program to evaluate the 1st derivative of a function at any given point

Writing C programs for numerical differentiation is interesting and fun. Here is one that I wrote years back. Enjoy!

## C Program to evaluate forward difference

Below is a C program to evaluate forward difference and thus print a forward difference table for n function values –

## C program to convert a postfix string to prefix form

Below is sample C program to convert a postfix string to prefix form. Also included is detailed flow chart of the program and dry run for couple different use cases.

## C program to convert a prefix string to infix form

Below is sample C program to convert a prefix string to infix form. Also included is detailed flow chart of the program and dry run for couple different use cases.

## Example for Preorder and Postorder traversal of a Binary tree

Below is an example that I prepared for preorder and postorder traversal of a Binary Tree – enjoy!

## Traversing a Binary Tree in Postorder

Below is the algorithm and C routine for traversing a Binary Tree in postorder.