Tuesday, 23 September 2014

C++ Design Patterns

 Singleton Design Pattern -> creational pattern
a class has only one instance, and provide a global point of access to it.
initialization on first use only
//mysingletone.C

#include<iostream>

using namespace std;

class singletone {
        singletone () {} //Constructor made Private
        singletone(const singletone &);  //Copy Constructor Hidden and Not Implemented
public:
        void display();
        static singletone &getstring()  //returns class object singletone
        {
                static singletone singObj;
                return singObj;
        }
};

void singletone::display()    //becomes singletone.display();
{
        cout << "Welcome to Karwar" << endl;
        return;
}
int main()
{
        cout << "singleton code" << endl;
        singletone::getstring().display();

return 0;
}

Result:
singleton code 
Welcome to Karwar

//Singleton Design pattern using reference variable
//singletonwithpointer.C

#include<iostream>

using namespace std;

class singletonRef {
        static singletonRef  *singleObj;
        singletonRef() {}
        singletonRef(const singletonRef &);
public:
        void display ();
        static singletonRef &getstring ()
        {
                if( singleObj == 0)
                singleObj = new singletonRef();
                return *singleObj;
        }
};

singletonRef *singletonRef::singleObj = 0;

void singletonRef::display ()
{
        cout << "Welcome To Karwar" << endl;
}


int main ()
{
        cout << "singleton using pointer" << endl;
        singletonRef::getstring().display ();
        return 0;
}
Result:
singleton using pointer
Welcome to Karwar



//singleton design pattern using Pointer
//singleusingpointer.C

#include<iostream>

using namespace std;

class singletonRef {
        static singletonRef  *singleObj;
        singletonRef() {}
        singletonRef(const singletonRef &);
public:
        void display ();
        static singletonRef *getstring ()
        {
                if( singleObj == 0)
                singleObj = new singletonRef();
                return singleObj;
        }
};

singletonRef *singletonRef::singleObj = 0;

void singletonRef::display ()
{
        cout << "Welcome to Karwar" << endl;
}


int main ()
{
        cout << "singleton using pointer" << endl;
        singletonRef::getstring()->display ();
        return 0;
}
Result:
singleton using pointer
Welcome to Karwar

Tuesday, 12 August 2014

Promotional Hierarchy, structure and union

Promotional Hierarchy of Fundamental data types

long Double                                                      Highest
Double
float
unsigned long int  unsigned long
long int   or long
unsigned int
int
unsigned short int  or unsigned short
short  or short int
unsigned char
char
bool                                                                 Lowest

Conversion from highest type to lowest type will result in loss of data.

//sizeofstructunion.C


int main()
{
   struct {
        char a[20];
        int n;
        union{
                double b;
                struct {
                        char d[15];
                        float e;
                }x;
        }y;
   }z;

   cout << "z.y.x size: " << sizeof(z.y.x) << endl;
   cout << "z.y size: " << sizeof(z.y) << endl;
   cout << "z size: " << sizeof(z) << endl;

    return 0;
}
result:
z.y.x size: 20 // char  array size is 15, float size 4, consider alignment(padding). multiply the size of float to equalize or exceed array size of 15. i.e 4*4=16 (here we got one more than 15). Hence size of struct is 16 of array and 4 of float. 4+16= 20. 
z.y size: 24 // size of struct member (20 bytes)in union is more than double . double b size is 8 bytes. Consider alignment(padding). Multiply the size of double to equalize or exceed the size of struct. Hence we get 8*3= 24.
z size: 48 // sizeof union + char a + int n -> 24+ 20+4 = 48.


//structdeclaration.C
#include<iostream>
using namespace std;

struct test {
        static  int a;
        int b;
        int c;
}obj;
int test::a=10;
int main()
{
 cout << "test" << endl;
cout << "now a:" << obj.a  << endl;
cout << "now b:" << obj.b << endl;
cout << "now c:" << obj.c;
return 0;
}

 

//declare a variable

extern int val;  //declaration of a variable

int iglobal;  // declaration as well as definition, coz global variables intialized to zero
int localVariable; // declaration as well as definition coz local variable are having garbage values.

 in C programming/ C++ programming, global structure members are initialized to zero.

local structure in C/C++ structure members will have garbage value.

Saturday, 26 July 2014

sizeof operator


//findreferencesize.C

#include<iostream>
using namespace std;


using namespace std;
struct student
{
        static int i;
        static int j;
}s;



int *x = new int(11);
int*  &j = x;
cout << "x: " << x << endl;
cout << "&x: " << &x << endl;
cout << "j: " << j << endl;
cout << "&j: " << &j << endl;
delete(x);
x = NULL;
cout << "x: " << x << endl;
cout << "&x: " << &x << endl;
cout << "j: " << j << endl;
cout << "&j: " << &j << endl;
cout << "size " << sizeof(&j) << endl;
cout << "size " << sizeof(x) << endl;
cout << "size " << sizeof(s) << endl;
cout << "size " << sizeof(s.i) << endl;
static int q;
cout << "size " << sizeof(q) << endl;

    return 0;
}
result:
x: 0x7f9359c000e0
&x: 0x7fff52cbcae0
j: 0x7f9359c000e0
&j: 0x7fff52cbcae0
x: 0
&x: 0x7fff52cbcae0
j: 0
&j: 0x7fff52cbcae0
size 8
size 8
size 1
size 4
size 4


//findsize.C

#include<iostream>
using namespace std;

struct bstree{
    static int info;
    bstree *left;
    bstree *right;
}obj;


int main()
{
    cout << "sizeof int is :" << sizeof(int) << endl;
    cout << "sizeof struct member pointer: " << sizeof(obj.left) << endl;
    cout << sizeof( bstree) << endl;

return 0;
}
result:

sizeof int is :4
sizeof struct member pointer: 8
16

//nonstatic.C 
#include<iostream>
using namespace std;


struct bstree{
    int info;
    bstree *left;
    bstree *right;
}obj;

int main()
{
    cout << "sizeof int is :" << sizeof(int) << endl;
    cout << "sizeof struct member pointer: " << sizeof(obj.left) << endl;
    cout << sizeof( bstree) << endl;

   cout << "static in size: ";

    static int x;
    cout << sizeof(x) << endl;


return 0;
}
result:

sizeof int is :4
sizeof struct member pointer: 8
24
static in size: 4
NOTE:C Program does allow storage type in structure, Above programs are in C++.
below is the code written in C.

//structsize.c

#include <stdio.h>
#include <stdlib.h>



struct node {
        static int val;
};

int main()
{
    struct node obj;

    printf("%d", sizeof(obj));

    return 0;
}

result:
 type name does not allow storage class to be specified.


//notallowed_initialization.c
#include<stdio.h>

int main()
{
     struct node
    {
        char name[] = "C skills";
        int  rank = 200;
    };

    struct node *ptr;
    printf("%d ", ptr->rank);
    printf("%s", ptr->name);
    getchar();
    return 0;
}
result:
Compiliation error
Reason:
When we declare a structure or union, we actually declare a new data type suitable for our purpose. So we cannot initialize values as it is not a variable declaration but a data type declaration.

//staticinstruct.c
#include<stdio.h>
struct node
{
    int m;
    static int n;
};

int main()
{
    printf("%d", sizeof(struct node));
    return 0;
}
    return 0;
}
result:
Compiliation error
Reason:
In C, struct and union types cannot have static members. In C++, struct types are allowed to have static members, but union cannot have static members in C++ also.

//sizeofstrucunion.c
#include<stdio.h>
int main()
{
    struct { 
          short s[5];
          union { 
               float y; 
              long z; 
         }u; 
    } t;

   printf("%d\n", sizeof(t.u));

   printf("%d\n", sizeof(t));

   printf("%d", sizeof(long));
   return 0;
}
result:
8
24
8
Reason: long is 8 bytes. short is 2 bytes. Hence short s[5] is 5 *2 which is 10, but here size is allocated based on alignment or padding for short s[5] in terms of long z which is 8bytes .
i.e multiples of 8. When we declare a union, memory allocated for union is equal to memory required for largest member of it, and all members share this same memory space. Hence for short s[5] with padding the size allocated 16 bytes, thus totaling to 16 + 8 =24.

//structasmember.c

#include<stdio.h>
int main()
{
     struct node
    {
        int x;
        struct node next;
    };

   struct node temp;
       temp.x = 10;
       temp.next = temp;
       printf("%d", temp.next.x);

  return 0;
}
result:structasmember.c|48|error: field has incomplete type 'struct node'|
Compiliation error

A structure cannot contain a member of its own type because if this is allowed then it becomes impossible for compiler to know size of such struct. Although a pointer of same type can be a member because pointers of all types are of same size and compiler can calculate size of struct




Tuesday, 22 July 2014

C++ Operator overloading using friend function

//opoverloadfriendfunc.C

#include<iostream>
using namespace std;

class traffic {
        int left, right;
public:
        traffic() {}
        traffic(int lt, int rt)
        {
                left = lt;
                right = rt;
        }
        void show()
        {
                cout << "left :" << left;
                cout << " right :" << right << endl;
        }

        friend traffic operator+(traffic ob1, traffic ob2);
        friend traffic operator-(traffic ob1, traffic ob2);
        friend traffic operator++(traffic &ob);
        friend traffic operator--(traffic &ob);
};

traffic operator+(traffic ob1, traffic ob2)
{
        traffic temp;
        temp.left = ob1.left + ob2.left;
        temp.right = ob1.right + ob2.right;

        return temp;
}

traffic operator-(traffic ob1, traffic ob2)

{
        traffic temp;

        temp.left = ob1.left - ob2.left;
        temp.right = ob1.right - ob2.right;

        return temp;
}
traffic operator++(traffic &ob)
{
        ob.left++;
        ob.right++;

        return ob;
}

traffic operator--(traffic &ob)
{
        ob.left--;
        ob.right--;

        return ob;
}

int main()
{
        traffic ob1(5, 10), ob2(10 , 20);

        ob1.show();
        ob2.show();

        ob1 = ob1+ob2;

        ob1.show();
       
        cout << "**********************" << endl;

        ob1 = ob1-ob2;

        ob1.show();
        cout << "**********************" << endl;
        ++ob1;

        ob1.show();
        cout << "**********************" << endl;
        --ob2;

        ob2.show();
        return 0;
}

result:
left :5 right :10
left :10 right :20
left :15 right :30
**********************
left :5 right :10
**********************
left :6 right :11
**********************
left :9 right :19

Monday, 21 July 2014

Sorting Algorithms

//Ascending order selection sort program


#include<iostream>
using namespace std;
#define SIZE 10

int main()
{
        int arr[SIZE];
        int i, j, temp;
        cout << "enter ten elements" << endl;
        for (i =0; i< SIZE ; i++)
        {
        cin >> arr[i];
        }

        cout << "elements enetered are: \n";
        for (i =0; i< SIZE ; i++)
        {
            cout << arr[i] << endl;
        }

        for (i= 0; i < SIZE-1; i++)
        {
            for (j = i+1; j <SIZE; j++)
            {
                if (arr[i] > arr[j])
                {
                    temp = arr[i];
                    arr[i] = arr[j];
                    arr[j]= temp;
                }
            }
        }
        cout << endl << endl << "sorted array using selection sort \n";

        for (i =0; i<SIZE ; i++)
            cout << arr[i] << endl;
    return 0;
}

result:

enter ten elements
500
1
987
456
32
54
23
965
56
733
elements enetered are: 
500
1
987
456
32
54
23
965
56
733

sorted array using selection sort 
1
23
32
54
56
456
500
733
965
987

//Ascending order Bubble Sort Program

#include<iostream>
using namespace std;
#define SIZE 10

int main()
{
            int arr[SIZE];
            int temp, i, j;
            cout << "enter ten elements" << endl;
            for (i =0; i< SIZE ; i++)
            {
            cin >> arr[i];
            }

            cout << "elements enetered are: \n";
            for (i =0; i< SIZE ; i++)
            {
                cout << arr[i] << endl;
            }

            for (i =0; i < SIZE-1; i++)
            {
                for(j=0; j < SIZE-1-i; j++)
                {
                    if (arr[j]>arr[j+1])
                    {
                        temp = arr[j];
                        arr[j] = arr[j+1];
                        arr[j+1]= temp;
                    }

                }
            }

            cout << endl ;
            cout << "sorted array using bubble sort \n";

            for (i =0; i<SIZE ; i++)
            cout << arr[i] << endl;
    return 0;
}

result:
enter ten elements
54
23
332
4
5
77
887
467
344
22
elements enetered are: 
54
23
332
4
5
77
887
467
344
22

sorted array using bubble sort 
4
5
22
23
54
77
332
344
467
887

//inserting an element at proper place in sorted array

#include<iostream>
using namespace std;
#define SIZE 10

int main()
{
            int arr[SIZE];
            int  i, item;
            cout << "enter  nine elements in sorted order" << endl;
            for (i =0; i< SIZE-1 ; i++)
            {
            cin >> arr[i];
            }

            cout << "Nine elements enetered are: \n";
            for (i =0; i< SIZE-1 ; i++)
            {
                cout << arr[i] << endl;
            }

            cout << "enter an item to be inserted";
            cin>> item;

            for(i = SIZE-2; item < arr[i]; i--)
            {
                    arr[i+1] = arr[i];
            }
            arr[i+1] = item;

            for (i =0; i< SIZE ; i++)
            {
                cout << arr[i] << endl;
            }

    return 0;
}

result:
enter  nine elements in sorted order
2
4
6
7
8
9
15
20
50
Nine elements enetered are: 
2
4
6
7
8
9
15
20
50
enter an item to be inserted12
2
4
6
7
8
9
12
15
20
50

//Ascending order insertion sort program

#include<iostream>
using namespace std;
#define SIZE 10

int main()
{
            int arr[SIZE];
            int  i, k,item;
            cout << "Enter  elements to sort" << endl;
            for (i =0; i< SIZE ; i++)
            {
            cin >> arr[i];
            }

            cout << "Ten elements enetered are: \n";
            for (i =0; i< SIZE ; i++)
            {
                cout << arr[i] << endl;
            }

            for (k=1; k<SIZE; k++)
            {
                item = arr[k];
                for(i = k-1; item <arr[i] && i>=0; i--)
                {
                    arr[i+1] = arr[i];
                }
                arr[i+1]= item;
            }
            cout << "sorted array is:\n";
            for(i=0; i < SIZE; i++)
                cout << arr[i] << endl;

    return 0;
}

result:

Enter  elements to sort
45
67
3
23
12
444
765
235
44
466
Ten elements enetered are: 
45
67
3
23
12
444
765
235
44
466
sorted array is:
3
12
23
44
45
67
235
444
466
765

Saturday, 19 July 2014

Binary Search

//Searching an element through binary search in C++

#include<iostream>
using namespace std;
#define SIZE 10

int main()
{
            int arr[SIZE];
            int low,  up, mid, item , i;
            cout << "enter 10 Elements in SORTED Order" << endl;
            for (i =0; i <SIZE; i++)
            {
             cin >> arr[i];
            }

            for (i =0 ; i < SIZE ; ++i)
            cout << arr[i] << endl;

            cout << "enter item to be searched\n";
            cin >> item;
            low = 0;
            up = SIZE -1;
            mid = -1;

            while(low<= up && item != arr[mid] )
            {
                mid = (low + up)/2;

                if (item < arr[mid])
                    up = mid -1;

                if (item > arr[mid])
                    low = mid +1;

                if (item == arr[mid])
                    cout << "your search element found at position:" << mid << endl;

                if (low>up)
                    cout << "your search element not found" << endl;
        }
    return 0;
}

result:
enter 10 Elements in SORTED Order
1 2 3 4 5 6 7 8 9 99
1
2
3
4
5
6
7
8
9
99
enter item to be searched
7
your search element found at position:6



Friday, 18 July 2014

C++ Basic Skills


//skillone.C
#include <iostream>
using namespace std;

int main()
{
    int a =30, b =5;
    if (a<10)
        a=a-5;
    b=b+5;
    cout << "Value of a and b is :" <<  a << " and "  << b << endl;
    return 0;
}

result 30 and 10

//skilltwo.C
#include<iostream>
using namespace std;

int main ()
{

 int a = 8, b = 0, c = 0;
    if(!a < 20 && !b || c)
        cout << "check success" << endl;
    else
        cout << "check failure" << endl;

    return 0;
}

result: check success

//skillthree.C
#include<iostream>
using namespace std;
int main()
{
 int i= 1, j=9;

         if (i>=5 && j<5);

         i = j+2;

         cout << " i val " << i <<endl;

    return 0;
}

result i val 11

//skillfour.C
#include<iostream>
using namespace std;
int main()
{
 int a=0, b=0;

         if(!a)
         {
             b =!a;
             if(b)
                a =!b;
         }
         cout << " a  and b val are: " << a << "  " << b << endl;
    return 0;
}

result : a  and b val are: 0  1

//skillfive.C
#include<iostream>
using namespace std;

int main ()
{
int a=5;
         begin:
             if (a)
             {
                 cout << " " << a ;
                 a--;
                 goto begin;
             }

    return 0;
}

result: 5 4 3 2 1

//skillsix.C
#include<iostream>
using namespace std;

int main()
{
int a=2, x=10;
if(a == 2)
    if(x== 8)
        cout <<"a equal 2 and x equal 8" << endl;
else
    cout << "a not equal  to 2" << endl;
    return 0;
}

result : a not equal to 2

//skillseven.C
#include<iostream>
using namespace std;

int main()
{
int a =6, b =4;
    while (a+b)
    {

        cout << a  << " " << b << endl;
        a = a/2;
        b%=3;
    }
    return 0;
}

result :
0 1
0 1
0 1
0 1
0 1
0 1
0 1
0 1
0 1
0 1
0 1
0 1
0 1
0 1
0 1
0 1
0 1
0 1
.........
value of b never becomes zero and hence the condition never becomes false.

//skilleight.C
#include<iostream>
using namespace std;

int main()
{
 int a =9;
    if (a = 5)
        cout << "hurrah I won" << endl;
    else
        cout << "I have to try now" << endl;
    return 0;
}

result:
hurrah I won

//skillnine.C
#include <iostream>
using namespace std;
int main()
{
int i, j, x =0;
        for (i = 0; i<5;i++)
            for(j=i; j>0 ; j--)
                x =i+j+1;
        cout << "x val: " << x << endl;
    return 0;
}

result: x val: 6

//skillten.C
#include <iostream>
using namespace std;

int main()
{
int i = 0, count = 0 ;

        while(i++)
        {
            count++;
            cout << "val of i from start: "<< count;
            if(count == 6)
                break;
        }
        cout << "count : " << count;

    return 0;
}

result:
count : 0

//skilleleven.C
#include <iostream>
using namespace std;


int main ()
{
int j, count = 0;
        for (j =0;  j<5; j++)
        {
         int j = 0;
         while(j++ < 5)
            count++;
        }

        cout << "count val: " << count << endl;

    return 0;
}

result:
count val: 25

//skilltwelve.C
#include <iostream>
using namespace std;

int main ()
{
int j, count = 0;
        for (j =0;  j<5; j++)
        {
        // int j = 0;
         while(j++ < 5)             // 0 , 1, 2, 3, 4
            count++;
        }

        cout << "count val: " << count << endl;
    return 0;
}

result:
count val: 5


//skillthirteen.C
#include <iostream>
using namespace std;

int main()
{

int i;
        for (i =1; i<10;i++)
        {
            if (i== 3)
                continue;
            cout << i << endl;
        }
    return 0;
}


result:

1
2
4
5
6
7
8
9

Note value 3 is skipped because of continue statement.

//skillfourteen.C
#include<iostream>
using namespace std;
int main()
{

int i=1;
        while (i<10)
        {
            if (i==3)
                continue;
            cout << i << endl;
           i++;
        }
    return 0;
}

result:
this program print 1 2 and then goes into an infinite loop 

//skillfifteen.C
#include<iostream>
using namespace std;

int main()
{
 char ch ='A';
        while(ch <='D')
        {
            switch(ch)
            {
            case 'A' :
            case 'B':
                        ch++;
                        continue;
            case 'C' :
            case 'D' :
                ch++;
            }
            cout << ch << endl;
        }
    return 0;
}

result:
D
E
here continue statement is used inside while loop. Hence on continue statement execution, the control goes to while loop condition check and thus works fine.

//skillsixteen.C
#include<iostream>
using namespace std;
int main()
{
char ch='A';
        switch(ch)
        {
        case 'A':
        case 'B':
            ch++;
            continue;

        case 'C' :
        case 'D':
            ch++;
        }
    return 0;
}

result:
Compiliation error
'continue' statement not in  loop statement
 








Thursday, 17 July 2014

C++ Operator Overloading

//opoverloadfunc.C

#include<iostream>

using namespace std;

class traffic {
        int left, right;

        public:
        traffic() {}  //empty constructor
        traffic(int lt, int rt)
        {
                left = lt;
                right = rt;
        }

        void show()
        {
                cout << "left: " << left << endl;
                cout << "right: " << right << endl;
        }
        //operator overloading functions for + , - , * , / , = , ++ , --
        traffic operator+(traffic ob1);
        traffic operator-(traffic ob1);
        traffic operator*(traffic ob1);
        traffic operator/(traffic ob1);

        traffic operator++();
        traffic operator--();

        ~traffic()
        {
                cout << "in destructor" << endl;
        }
};
traffic traffic::operator+(traffic ob1)
{
        traffic temp;

        temp.left   = left + ob1.left;
        temp.right  = right + ob1.right;

        return temp;
}

traffic traffic::operator-(traffic ob1)
{
        traffic temp;
        temp.left = left - ob1.left;
        temp.right = right - ob1.right;
        return temp;
}

traffic traffic::operator*(traffic ob1)
{
        traffic temp;
        temp.left = left * ob1.left;
        temp.right = right * ob1.right;

        return temp;
}

traffic traffic::operator/(traffic ob1)
{
        traffic temp;
        temp.left = left/ob1.left;
        temp.right = right/ob1.right;

return temp;
}

traffic traffic::operator++()
{
        left++;
        right++;

        return *this;
}

traffic traffic::operator--()
{
        left--;
        right--;

        return *this;
}


int main()
{
        traffic ob1(10, 20), ob2(2,4);
        ob1.show();
        ob2.show();
        ob1 = ob1+ob2;
        ob1.show();
        ob1 = ob1 - ob2;
        ob1.show();

++ob1;
        ++ob2;

        ob1.show();
        ob2.show();
        --ob1;
        --ob2;
        ob1.show();
        ob2.show();


        ob1 =(ob1*ob2);
        cout << "multi" << endl;
        ob1.show();
        ob1 = ob1/ob2;
        ob1.show();
        return 0;
}