Tuesday, 3 December 2019

Sample Programs and Singleton Design Pattern

# include<iostream>
# include<stdio.h>
using namespace std;

class TInstanceCount
{
static int _instanceCount;
public:
TInstanceCount(void)
{
++TInstanceCount::_instanceCount;
}
static int GetInstanceCount(void)
{
return TInstanceCount::_instanceCount;
}
};
int TInstanceCount::_instanceCount=0;

int main(void)
{
TInstanceCount ob1,ob2,ob3,ob4;
int a =ob1.GetInstanceCount();
printf("%d\n",a);
return 0;
}





# include<stdio.h>
# include<iostream>

using namespace std;

class TSingleton
{
private:
int _num1;
int _num2;
private:
TSingleton(const int num1,const int num2):_num1(num1),_num2(num2)
{};
public:
static TSingleton& getInstance(const int num1,const int num2)
{
static TSingleton singletonInstance(num1,num2);
return singletonInstance;
}

void PrintRecord(void)
{
cout<<"Num1 : "<<this->_num1<<endl;
cout<<"Num2 : "<<this->_num2<<endl;
}
};
int main(void)
{
TSingleton& s1=TSingleton::getInstance(500,600);
s1.PrintRecord();
TSingleton& s2=TSingleton::getInstance(100,200);
s2.PrintRecord();
return 0;
}





# include<iostream>
# include<stdio.h>
using namespace std;
class TSingleton
{
int _num1;
int _num2;
static TSingleton* _ptr;

private:
TSingleton(const int num1,const int num2):_num1(num1),_num2(num2)
{ }
public:
static TSingleton* getInstance(const int num1,const int num2)
{
if(TSingleton::_ptr==NULL)
{
TSingleton::_ptr=new TSingleton(num1,num2);
return TSingleton::_ptr;
}

}
void printRecord(void)
{
cout<<"NUm1 : "<<this->_num1<<endl;
cout<<"Num2 : "<<this->_num2<<endl;
}
static void clear(void)
{
if(TSingleton::_ptr!=NULL)
delete TSingleton::_ptr;
TSingleton::_ptr=NULL;
}
};
TSingleton* TSingleton::_ptr=NULL;
int main(void)
{
TSingleton* ptr1=TSingleton::getInstance(100,200);
TSingleton* ptr2=TSingleton::getInstance(500,600);
ptr1->printRecord();
ptr2->printRecord();
TSingleton::clear();
return 0;
}


# include<stdio.h>
# include<iostream>
using namespace std;

int sum(int num1,int num2)
{
return num1+num2;
}
int sub(int num1,int num2)
{
return num1-num2;
}

int menu_list(void)
{
int choice;
cout<<"0.Exit"<<endl;
cout<<"1.Sum"<<endl;
cout<<"2.Sub"<<endl;
cout<<"Enter Choice: ";
cin>>choice;
return choice;
}

void accept_record(int & number)
{
cout<<"Enter Number : ";
cin>>number;
}
void print_record(const int& result)
{
cout<<"Result :"<<result<<endl;
}
int main(void)
{
int choice;
int num1,num2;
while((choice=::menu_list())!=0)
{
int(*ptr)(int,int)=NULL;
int result=0;
switch(choice)
{
case 1:
ptr=&sum;
break;
case 2:
ptr=&sub;
break;
}
if(ptr!=NULL)
{
::accept_record(num1);
::accept_record(num2);
result=ptr(num1,num2);
::print_record(result);
}
}
return 0;
}




Sample Programs

# include<iostream>
using namespace std;

class Test
{
private:
int num1;
static const int num2;
public:
Test(void)
{
this->num1=10;
}
void PrintRecord(void)
{
cout<<"Num1 : "<<this->num1<<endl;
cout<<"Num2 : "<<this->num2<<endl;
}
};
const int Test::num2=1000;
int main(void)
{
Test t1;
t1.PrintRecord();
return 0;
}




# include<iostream>
using namespace std;

class A
{
public:
static void F1(void)
{
cout<<"A::F1"<<endl;
}
};

class B
{
public:
static void F2(void)
{
cout<<"B::F2"<<endl;
}
static void F3(void)
{
A::F1();
F2();
B::F2();
cout<<"B::F3"<<endl;
}
};

int main(void)
{
B::F3();
return 0;
}



# include<iostream>
using namespace std;
#include <string>

namespace NEmployee
{
class TEmployee
{
private:
string _name;
int _empid;
float _salary;
static int _count;
public:
TEmployee(void)
{
this->_name=" ";
this->_empid=++TEmployee::_count;
this->_salary=0;
}
TEmployee(const string name,const float salary)
{
this->_name=name;
this->_empid= ++TEmployee::_count;
this->_salary=salary;
}
static void SetCount(int count)
{
TEmployee::_count=count;
}
void PrintRecord()
{
cout << this->_name<<" "<<this->_empid<<" "<<this->_salary << "\n";
}
};
int TEmployee::_count;
int main(void)
{
using namespace NEmployee;
TEmployee::SetCount(1000);
TEmployee emp1("ABC",10000.00f);
emp1.PrintRecord();
return 0;
}




# include<iostream>
using namespace std;
#include<string>

class TPerson
{
private:
string _name;
int _age;

public:
TPerson(void)
{
this->_name="";
this->_age=0;
}
TPerson(const string name,const int age):_name(name),_age(age)
{}
void PrintRecord(void)const
{
cout<<"Name: "<<this->_name<<endl;
cout<<"Age: "<<this->_age<<endl;
}
};
class TEmployee:public TPerson
{
private:
int _empid;
float _salary;
public:
TEmployee(void):_empid(0),_salary(0)
{}
TEmployee(const string name,const int age,const int empid,const int salary):TPerson(name,age),_empid(empid),_salary(salary)
{}
void PrintRecord(void)const
{
TPerson::PrintRecord();
cout<<"EmpId: "<<this->_empid<<endl;
cout<<"Salary: "<<this->_salary<<endl;
}

};
int main(void)
{
TEmployee emp("ABC",23,123,1200);
emp.PrintRecord();
return 0;
}


Sunday, 1 December 2019

Sorting Algorithm

/***************************************************
 * Author : Ajit
 *
 * Description : This file contains implementation of selection sort and insertion sort Algorithm
 *
 /**************************************************/


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Diagnostics;

namespace Sorting_Techniques
{
    class Sorting
    {

        /*****************************************************************************/
        /* Method Print
        /*
        /* Description This functions prints the array elements .
        /*
        /* Paremeters  int[] a -array elemets to be printed
                       n - No of elements in Array
        /* Return Void
        /******************************************************************************/

        public static void print(int[] a, int n)
        {
            Console.Write("ARR: ");
            for (int i = 0; i < n; i++)
            {
                Console.Write(a[i]);
                Console.Write(' ');
            }
            Console.Write("\n");
        }

        /*****************************************************************************/
        /* Method Selection Sort
        /*
        /* Description This functions sorts the array elements .
           In a set oF N elements find out the location of the minimum elements and replace it with the location of first element.
           Repeat above step for N-1 elements untill the list is sorted.
        /*
        /* Paremeters  int[] a -array to be sorted
                       n - No of elements in Array
        /* Return Void
        /******************************************************************************/
        public static void selection(int[] a, int n)
        {
            int i;
            int j;
            for (i = 0; i < n - 1; i++)
            {
                for (j = i + 1; j < n; j++)
                {
                    if (a[i] > a[j])
                    {
                        int t = a[i];
                        a[i] = a[j];
                        a[j] = t;
                    };
                }
            }
        }

        /*****************************************************************************/
        /* Method Insertion Sort
        /*
        /* Description This functions sorts the array elements .
           A sublist or Sorted array is maintained which is always sorted .
           N-1 pass are required to sort N elements.
           In each pass , we insert current element at appropriate place so that the elements in current range are in order .s
           Each pass has k comparison where k is the pass no.
        /*
        /* Paremeters  int[] a -array to be sorted
                       n - No of elements in Array
        /* Return Void
        /******************************************************************************/

        public static void insertion(int[] a, int n)
        {
            int i;
            int j;
            int temp;
            for (i = 1; i < n; i++)
            {
                temp = a[i];
                for (j = i - 1; j >= 0 && a[j] > temp; j--)
                {
                    a[j + 1] = a[j];
                }
                a[j + 1] = temp;
            }
        }

        public static int RandomNumber(int min, int max)
        {

            Random random = new Random(DateTime.Now.Ticks.GetHashCode());
            return random.Next(min,max);
        }

        static void Main(string[] args)
        {
            Stopwatch myTimer = new Stopwatch();

            /*  Already Sorted Array*/
            int [] arr_sel_asc =new int [500];
            for (int i = 0; i <= arr_sel_asc.Length-1; i++)
                arr_sel_asc[i] = i;
            int[] arr_ins_asc = new int[500];
            for (int i = 0; i <= arr_ins_asc.Length-1; i++)
                arr_ins_asc[i] = i;

            Console.WriteLine("Array before Sorting");
            print(arr_sel_asc, 500);
            myTimer.Start();
            /* Calling Selection Sort Method for Sorted Array*/
            selection(arr_sel_asc, 500);
            myTimer.Stop();
            Console.WriteLine("Time Taken for Selection Sort for Sorted Array : {0}  ", myTimer.Elapsed);
            Console.WriteLine("Array After Selection Sort");
            print(arr_sel_asc, 500);
            myTimer.Reset();
            myTimer.Start();
            insertion(arr_ins_asc, 500);
            myTimer.Stop();
            Console.WriteLine("Time Taken for Insertion Sort for sorted Array : {0}  ", myTimer.Elapsed);
            Console.WriteLine("Array After Insertion Sort");
            print(arr_ins_asc, 500);

            /* Sorted In Opposite Order */

            int[] arr_sel_desc = new int[500];
            for (int i = arr_sel_desc.Length-1; i >=0; i--)
                arr_sel_desc[i] = arr_sel_desc.Length - 1 - i;
            int[] arr_ins_desc = new int[500];
            for (int i = arr_ins_desc.Length-1; i >=0 ; i--)
                arr_ins_desc[i] = arr_sel_desc.Length - 1 - i;

            Console.WriteLine("Array before Sorting");
            print(arr_sel_desc, 500);
            myTimer.Reset();
            myTimer.Start();
            /* Calling Selection Sort Method for Sorted Array in opposite order*/
            selection(arr_sel_desc, 500);
            myTimer.Stop();
            Console.WriteLine("Time Taken for Selection Sort for Sorted Array in Opposite order : {0}  ", myTimer.Elapsed);
            Console.WriteLine("Array After Selection Sort");
            print(arr_sel_desc, 500);
            myTimer.Reset();
            myTimer.Start();
            insertion(arr_ins_desc, 500);
            myTimer.Stop();
            Console.WriteLine("Time Taken for Insertion Sort for sorted Array in Opposite Order : {0}  ", myTimer.Elapsed);
            Console.WriteLine("Array After Insertion Sort");
            print(arr_ins_desc, 500);


            /* Array element in Random Order*/
            int[] arr_ran = new int[500];
            for (int i = 0; i <= arr_ran.Length-1; i++ )
            {
                arr_ran[i] = RandomNumber(1, 500);
            }

            int[] arr_ran_sel = new int[500];

            for (int i = 0; i <= arr_ran_sel.Length-1; i++)
            {
                arr_ran_sel[i] = arr_ran[i];
            }

            int[] arr_ran_ins = new int[500];

            for (int i = 0; i <= arr_ran_ins.Length - 1; i++)
            {
                arr_ran_ins[i] = arr_ran[i];
            }

            Console.WriteLine("Array before Sorting");
            print(arr_ran_sel, 500);
            myTimer.Reset();
            myTimer.Start();
            /* Calling Selection Sort Method for Sorting array elements in random order*/
            selection(arr_ran_sel, 500);
            myTimer.Stop();
            Console.WriteLine("Time Taken for Selection Sort for Sorting array elements in Random order : {0}  ", myTimer.Elapsed);
            Console.WriteLine("Array After Selection Sort");
            print(arr_ran_sel, 500);
            myTimer.Reset();
            myTimer.Start();
            /* Calling Insertin Sort Method for Sorting array elements in Random order*/
            insertion(arr_ran_ins, 500);
            myTimer.Stop();
            Console.WriteLine("Time Taken for Insertion Sort for sorting array elements in Random Order : {0}  ", myTimer.Elapsed);
            Console.WriteLine("Array After Insertion Sort");
            print(arr_ran_ins, 500);

            Console.ReadKey();
        }
    }
}


Insertion sort perform less comparison than selection sort  depending on the degree of sortedness
of array.Selection sort must scan the remaining parts of the array when placing an element .Insertion sort only scans as many elements as necessary.
When array is already sorted or almost sorted , insertion sort performs in O(n) Time.
Overall insertion sort usually more efficient.
Below image shows time take by insertion sort and selection sort when array is sorted.





Below image Shows time taken by selection sort and insertion sort when arrays is in opposite order(Descending order).




Below image shows time taken by insertion sort and selection sort when arrays element in Random Order. 







Insertion Sort :

The data is sorted by inserting the data into a sorted location.
Insertion sort perform less comparison than selection sort  depending on the degree of sortedness  of array. 
The  time taken by insertion sort would be dependent on the input .Because sorting thousand numbers takes more time thant sorting 3 numbers .More over it is dependent on how the input is sorted .
But the runnig time of program grows with the size of input.

Assumptions:
Costant amount of time is required to execute each line of pseudocode .

for (i = 1; i < n; i++)                   //Execute N times    //Cost C1          
              {
                temp = a[i];                            //Execute N-1 times   //Cost C2
                for (j = i - 1; j >= 0 && a[j] > temp; j--)   //Execute minimum N-1 Times
                                                       //Execute maximum N(N-1)/2 Times
                                                       //Cost C3    
                {
                    a[j + 1] = a[j];                   //Execute maximum N(N-1)/2 Times 
                                                       //Cost C4
                }
                a[j + 1] = temp;                        //Execute N-1 times Cost C5
          }
As per above observation please find below time complexity
Best case complexity : O(n)
Worst Case: O(n^2)


Selection Sort :

The data is sorted by selecting and placing the consecutive elements in sorted location.
Selection sort must scan the remaining parts of the array when placing an element .

            for (i = 0; i < n - 1; i++)           //Execute N times    //Cost C1          
            {
                for (j = i + 1; j < n; j++)    //Execute N(N-1)/2 Times
                                                       //Cost C2    
                {
                    if (a[i] > a[j])           
                    {
                        int t = a[i];         //Execute N-1 times //Cost C3
                        a[i] = a[j];          //Execute N-1 times //Cost C3
                        a[j] = t;             //Execute N-1 times //Cost C3
                    };
                }
            }
      
Best Case complexity: O(n^2)
Worst Case Complexity : O(n^2)

Insertion sort is more efficient because you have to search the sorted section where the next element goes where as in selection sort you have to scan the entire unsorted part of the array.

Saturday, 30 November 2019

C++ Tutorial

OOPS

Its a programming methodology to organize complex system into small system with the help of class and object.

4 major elements /parts/pillars

There are 4 major pillars and 3 minor pillars of oops concept.

Major Pillars

1>Abstraction
2>Encapsulation
3>Modularity
4>Hierachy

By major , we mean that model without any one of these elements is not object oriented.

Minor Pillars

1 Typing /Polymorphism
2 Concurrency
3 Persistence

By minor we means that each of these elements is useful but not essential part of the object model

If language support all major pillars of oops then it is called object oriented programming Language.

Ex: Simula, Small Talk, C++, Java, Vb.net , Ruby

More than 2000 language in the world are object oriented.

If language support all four major pillar and all three minor pillars of oops then it is called pure object oriented language .

Ex: Small Talk, Java, C++

If language support atleast polymorphism and inheritance then it is considered as object oriented programming language .

Language which support some of the features of object oriented programming language but not all such language are called object based programming language .

ex: Visual Basic , Modula2, Ada.

Ada is first object based programming language .
Simula is first object oriented programming language.


Abstraction

It is a process of  getting essential things of the object.

Abstraction focus on essential characteristics of some object releative to the perspective of the viewer.

Giving call to the member function by using object of a class indicates abstraction programatically.

Encapsulation

Implementation of abstraction is called encapsulation.

Binding of data and code together is called encapsulation.

Class is the basic unit of encapsulation

Encapsulation represents internal representation of the object.

Abstraction and encapsulation is totally independent of each other .

Data Hiding / Information hiding

Its a process of declaring data member as a private or protected.

To achieve data hiding it is necessary to use encapsulation.

To achieve data security it is necessary to use data hiding .

Data Security :

Its a process of giving controlled access to the member of the class.

Modularity :

Its a process of dividing complex system into small small modules (Class)

Advantage of abstraction  :We try to minimise the complexity.

If we want to minimise module dependency we should use modularity.

There are two types of modularity

1> Logical Modularity
2>Physical Modularity

In C++ we can achieve logical modularity with namespace .

We can achieve physical modularity by dividing code into multiple files.

Typing /Polymorphism:

Typing is also called polymorphism.
Polymorphism is a greek word is a combination of two words (Poly and Morphism) (Many forms).

One interface having many behaviour this concept is called polymorphism.

Without changing interface if we want to add new functionality in existing system we should use polymorphism.

There are two types of polymorphism.

1>Compile time polymorphism
2>Run Time Polymophism

Compile Time polymophism/static polymophism/static binding/early binding/weak polymorphism/false polymorphism : 

If binding between object and function get reserved at compile time then it is called compile time polymorphism.

If call to the function gets reserved at compile time then it is called compile time polymorphism.

In C++ we can achieve compile time polymorphism by using two ways.

1 Function Overloading
2 Operator overloading.

Run Time Polymophism/dynamic polymophism/dynamic binding/Late binding /Strong polymorphism/True Polymorphism

If binding between object and function gets reserved at runtime then it is called run time polymorphism.

If call to the function gets reserved at run time then it is called run time polymorphism.

Concurrency : 

Its a process of executing multiple task simultaneously.

In object oriented programming language we can achieve multitasking with the help of multithreading.

Persistence : 

Process of storing state of the object either inside file or database .

In C++ we can achieve persistence with the help of file handling.

Hierachy : 

It is a major pillar of oops concept which is used to achieve code re-usability

Level or order or Ranking of abstraction is called Hierachy.

Types of hierachy :

There are 4 types of Hierachy.

1> has-a
2>is-a
3>use-a (dependency)
4>creates-a (instantiation)

we can achieve has a hierachy with the help of composition.
has a releationship is called part of releationship
Ex: Mobile has a sim card.  Maruti has Engine. House has bathroom.

we can achieve is a hierachy with the help of Inheritance.
Ex:House is a building . Car is a vehicle.

When object is a component or part of another object it is called composition.

For Ex : System unit has a motherboard, Mobile phone has  a simcard ,Room has a wall.

If we declare object of a class as a data member into another class then it is composition programatically.

Inheritance : 

It is a journey from Generalization to Specialization .

In C++ Parent class is called Base class and child class is called Derived Class.

class TPerson         //Base Class /Parent Class
{
};
class TEmployee::public TPerson      //Child Class/Derived Class
{
};

At the time of inheritance data member & member function of base class gets inherited into the derived class.

Following functions donot inherit into the derived class

1> Constructor
2> Destructor
3>Copy Constructor
4>Assignment operator function
5> Friend function

Size of derived class object = size of all non static data member declared in base class + size of all the non static data member declared in the derived class .

Static as well as non static members of base class gets inherited into derived class.

It is a process of acquiring properties and behaviour of base class by the derived class.

To access member of base class inside member function of derived class we should use class name and scope resolution operator.

If name of base class and derived class member function is same preference is always given to the derived class member function.

If we create object of derived class first base class constructor gets called and then derived class constructor gets called .

Destructor calling sequence is exactly opposite .

If you want to initialize data member of base class from derived class we should use constructor base initializer list.

In C++ we can call base class constructor from derived class constructor with the help of constructor base initializer list.

We can use constructor base initializer list and member initializer list together .

Constructor member initializer list is used to initialize data member of the same class .
Constructor base initializer list is used to initialize data members of the base class.

Constructor base initializer list indicates explicit call to constructor .




















E