## 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.

## Traversing a Binary Tree in Preorder

A binary tree can be traversed in two basic ways – preorder and postorder. Explained below is the process or preorder traverse of a binary tree with an algorithm and the actual C routine.

## Binary Tree

Binary Tree is a basic data structure that is used behind the scenes of all major technologies whether it’s a Database system or operating system, search engine, Bleeding edge AI systems, Big data or cloud based architectures.

## Simple HTTP log analyzer

Here is a simple light weight HTTP analyzer written in PHP. I wrote this to brush up my skills writing schedulers for a typical LAMP stack. Nothing fancy, there are more things to implement on detecting malicious requests, but this will get you started – <?php /** //Simple http log parser and report generation script…

## Stack Vs Heap

Stack and Heap refers to 2 distinct memory areas utilized by an executing program based on the data type of data that it deals at a point during its execution. Stack is that part of memory that a program uses to keep track of its execution flow. For example it stores the currently executed method…

## What is the purpose of static modifier?

Static modifier is commonly used in all programming languages. There are two distinct reasons for using the static modifier whether its C, Java, C#, PHP or Ruby – To access the class members without instantiating the object. eg: public class CutGrass{ public static void CleanMower(){ } } var endTheJob = CutGrass.CleanMower(); 2. To restrict the representation…

## Arrays Vs Lists – Which one to use?

Both Arrays and Lists helps us to store list of elements. But which one to choose is an important design decision that is directly related to application performance. Arrays are strongly typed – meaning they can only store data of one type. Use Arrays where the size and type of elements is fixed and we…

## C# File, Directory Manipulation

C# provide two versions of File, Directory manipulation options – 1) Static methods based and 2) Instance methods based. Static method based operations are provided by the File and Directory classes both derived from System.IO class. Instance method based operations are provided by the FileInfo and DirectoryInfo classes again both derived from System.IO class. File…

## MVC Architecture

MVC architecture has been in place since past 4 decades or so when GUI (Graphical Use Interfaces) started to be used widely. The idea is simple – to implement separation of concerns.  Plainly put, to separate 1) presentation (UI) 2) user interactions and 3) underlying data and logic/behavior. It might be easy to build a web…

## C# Program to find Age

Below is a C# program to find Age from a Date of Birth. Enjoy! public class Person    {        public string Name { get; set; }        public Person(DateTime birthdate)        {            BirthDate = birthdate;        }        public DateTime BirthDate { get; private set; }        public int Age{                        get {                 var timeSpan = DateTime.Today – BirthDate;                var years = timeSpan.Days / 365;                return years;                                        }        }    }    public class Program    {        public static void Main(string[] argvs)        {            var person = new Person(new DateTime(1998,2,14));                        Console.WriteLine(person.Age);        }    }

## Usage of params modifier in C#

Lets see how to use params modifier in C#. The perfect example is Calculator implementation. ‘params’ access modifier when used on a method argument, allows it to accept multiple argument values. Lets see the simple Calculator implementation below. As you can see, method argument ‘numbers’ is defined as integer array and being called out by…

Constructors need to be overloaded depending on what extend of data/properties need to be initialized in order to set the object to a particular state. Below a good example using a Customer / Orders example. Note that Customer constructor is overloaded in 3 different ways based on what data need to be initialized. Here we…

## Using LINQ in C#

LINQ or Language Integrated Query gives the capability to query objects and C# allows two distinctive ways to achieve this – You can either use LINQ query operators model or LINQ extension methods model with Lamba expressions on Func<> delegate. We have –  LINQ to Objects – Objects in memory eg: Collections ·       LINQ to Entities…

## Using DateTime in C#

Below is very simple usage of DateTime – class DateTimePr     {         static void Main(string[] args)         {             var datetime = new DateTime();             var now = DateTime.Now;             var today = DateTime.Today;             Console.WriteLine(now);             Console.WriteLine(today);             Console.WriteLine(now.Hour);             Console.WriteLine(now.ToLongDateString());             Console.WriteLine(now.ToString());         }     }

## Reading a file in C#

Below is a simple program in C# that reads a file and outputs the longest word in it. Enjoy! using System; using System.IO; using System.Collections.Generic; namespace <yourNS> {     class FilesNDirs     {         public static void Main(string[] argvs)         {             var path = @”C:\Users\deepesh\Desktop\Test\test.txt”;             var textFile = File.ReadAllText(path);             var words = textFile.Split(‘ ‘);             var wordlenpt = new string[100];             var wordlenarr = new List<int>();             foreach (var i in words)             {                 if (i.Length > 0)                 {                     wordlenarr.Add(i.Length);                     wordlenpt[i.Length] = i;                     Console.WriteLine(i);                 }             }             wordlenarr.Sort();             foreach (var i in wordlenarr)             {                 Console.WriteLine(i);             }             Console.WriteLine(“\n\nLargest word in the file is >>” +  wordlenpt[wordlenarr[wordlenarr.Count – 1]]);         }     } }

## Finding Lowest number from a List in C#

Below is a simple program to find the lowest number from a list of numbers – using System; using System.Collections.Generic; namespace GroundCSApp {     class GetSmallest     {         public static void Main(string[] argvs)         {             var numlist = new List<int> { 1, 2, 3, 4, 5, 6 };             var finallst = GetSmallests(numlist, 3);             foreach (var i in finallst)             {                 Console.WriteLine(i);             }         }         public static List<int> GetSmallests(List<int> lst, int cnt)         {             if (cnt > lst.Count)             {                 throw new ArgumentOutOfRangeException(“cnt”, “Count of numbers is  greater than the list count”);             }             var buff = lst;             var smalllst = new List<int>();             while (buff.Count > cnt)             {                 var min = GetiSmallest(buff);                 smalllst.Add(min);                 buff.Remove(min);             }             return smalllst;         }         public static int GetiSmallest(List<int> lsti)         {             var min = lsti[0];             for (var j = 1; j < lsti.Count; j++)             {                 if (lsti[j] < min)                 {…

## Simple C# Programs

Here is some basic, simple, handy C# programs for you to enjoy and refresh your memory – using GroundCSApp; using System; using System.Collections.Generic; using System.Linq; namespace GroundCSApp {     public enum ShippingMethod     {         Regular = 1,         Priority = 2,         Snail = 3     }     class Program     {         static void Main(string[] args)         {             //——————————————————-             //non -primitive/reference type eg: number              //array creation and assignment                          var numbers = new int[3];             numbers[0] = 23;             var numbers2 = numbers;             numbers[0] = 24;             Console.WriteLine(“Value of variable numbers is changed  and it is >>” + numbers[0]);             //——————————————————–             //——————————————————–             //non-primitive, immutable, string array creation assignment             var names = new string[3] { “John”, “Luke”, “Mark” };             //String Join example             var joinedName = string.Join(“,”, names);             Console.WriteLine(“\n\n” + joinedName);             var strArray = new string[] { “Text”, “Book”, “Light” };             var strArray2 = strArray;             //example for reference type where             //original value is modified             strArray2[0] = “Candle”;…

## Code Reuse via Composition in C#

Composition is a common object oriented concept that enables us to implement loose coupling as well as code-reuse. Lot of times we recommend our developers to use more composition and less inheritance due this very fact. Inheritance supports code-reuse, but makes application tightly coupled and creates long inheritance hierarchies that creates inter-dependencies. Inheritance implements a…

## Constructor Inheritance in C#

Like any other Object Oriented Programming language, C# does not allow parent constructor to be automatically inherited. It need to explicitly defined in the derived class. Below is an example to explain this – Below is the parent class – namespace ConstructorInh {     public class Fruit     {         private readonly string _color;         public Fruit(string color)         {             _color = color;             Console.WriteLine(“I am a Fruit with Color {0}”, _color);         }     } } Below is the…

## Dynamic Typing in C#

Well, C# provides this option to prove that it is flexible. If you are too fond of dynamic typing, use scripting languages such as PHP! Below is an example of how to use it – you will see that program will compile without errors and will display two different values for a as intended –…

## C# Generics

C# Generics are really useful when we want to reuse a class for different types and with constraints on what those types would be without rewriting those classes. C# allows at least 5 different kinds of Generics usage as related to the kind of constraints that we can use plus the most basic implementations such…

## C# Indexers

C# Indexers is a simple implementation of key/value pairs using Dictionary type. Below is a sample implementation of a telephone directory –TelephoneDirectory class using System.Collections.Generic; namespace Indexers {     public class TelephoneDirectory     {         private readonly Dictionary<string, string> _dictionary = new Dictionary<string, string>();         public string this[string key]         {             get { return _dictionary[key]; }             set { _dictionary[key] = value; }         }     } } As seen above, we use the ‘this[]’ notation to create the public property that sets/returns indexed value. We…

## C# Inheritance

We generally apply the concept of inheritance to implement a IS-A relationship. For example to implement a relationship that says an Apple is a Fruit or Earth is a cosmic object. We use inheritance very carefully so that it does not lead to long complex/un-maintainable object hierarchies, but to implement very specific object hierarchies with…

## C# Interfaces and how to implement loose coupling by Dependency (specific implementation of interface) injected via constructor overloading

Interface is a similar language construct such as class, but fundamentally different from a class. Some people claim that Interface is a way to implement multiple inheritance – this claim is also not true! If we were to implement inheritance via interfaces, then we would have re-used, but there is no code reuse while implementing…

## C# Abstract Classes Vs Interfaces

We use abstract classes when the base class can’t have concrete implementation and that we need the derived class to fully implement it. If at least one of the member is abstract, then the class will need to be declared as abstract. If a class derives an abstract class, then it needs to override all…

## Simple Stop Watch implementation in C#

Below is a simple stop watch implemented in C#, enjoy!StopWatch using System; namespace StopWatchApp {     public class StopWatch     {         public DateTime StarTime { get; set; }         public DateTime StopTime { get; set; }         public string ClockState { get; set; }         public void StartClock()         {             if(this.ClockState == “started”)                 throw new InvalidOperationException(“Invalid Operation”);             this.StarTime = DateTime.Now;             this.ClockState = “started”;         }         public void StopClock()         {             this.StopTime = DateTime.Now;             this.ClockState = “stopped”;         }         public TimeSpan ElapsedTime()         {             return this.StopTime – this.StarTime;         }     }  } Main Program using System; namespace StopWatchApp {     public class Program     {         public static void Main(string[] args)         {             Console.WriteLine(“Enter Start to Start the Clock,  Enter Stop to Stop the Clock to see the elapsed time.  Enter Quit to exit.”);             var clock = new StopWatch();             int alreadystarted = 0;             while (true)             {                 var inp = Console.ReadLine();                                 if (inp != “Quit”)                 {…

## Simple Workflow Engine Implementation in C#

Below is a simple implementation of work flow engine using interfaces and the concept of injecting overloaded class implementations via the dependent class method. The class constructor creates the List for storing the specific workflow implementations which are further executed.Interface – IWorkFlowActivities namespace WFEngine {     public interface IWorkFlowActivities     {         void Execute();     } } CarWorkflow using System; namespace WFEngine {     public class CarWorkflow : IWorkFlowActivities     {         public void Execute()…

## Data Types, Variables, Primitive Type, Non-Primitive Type, Reference Type and Value Type

Every 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….