Friday, November 23, 2012

queue using circular linked list

queue using circular linked list



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

struct node
{
    int info;
    struct node *link;
}*rear=NULL;

void insert(int item);
int del();
void display();
int isEmpty();
int peek();

main()
{
    int choice,item;
    while(1)
    {
        printf("1.Insert\n");
        printf("2.Delete\n");
        printf("3.Peek\n");
        printf("4.Display\n");
        printf("5.Quit\n");
        printf("Enter your choice : ");
        scanf("%d",&choice);

        switch(choice)
        {
         case 1:
            printf("Enter the element for insertion : ");
            scanf("%d",&item);
            insert(item);
            break;
         case 2:
            printf("Deleted element is %d\n",del());   
            break;
         case 3:
            printf("Item at the front of queue is %d\n",peek());
            break;
         case 4:
            display();
            break;
         case 5:
            exit(1);
         default:
            printf("Wrong choice\n");
        }/*End of switch*/
    }/*End of while*/
}/*End of main()*/

void insert(int item)
{
    struct node *tmp;
    tmp=(struct node *)malloc(sizeof(struct node));
    tmp->info=item;
    if(tmp==NULL)
    {
        printf("Memory not available\n");
        return;
    }
   
    if( isEmpty() ) /*If queue is empty */
    {
        rear=tmp;
        tmp->link=rear;
    }
    else
    {
        tmp->link=rear->link;
        rear->link=tmp;
        rear=tmp;
    }
}/*End of insert()*/

del()
{
    int item;
    struct node *tmp;
    if( isEmpty() )
    {
        printf("Queue underflow\n");
        exit(1);
    }
    if(rear->link==rear)  /*If only one element*/
    {
        tmp=rear;
        rear=NULL;
    }
    else
    {
        tmp=rear->link;
        rear->link=rear->link->link;
    }
    item=tmp->info;
    free(tmp);
    return item;
}/*End of del()*/

int peek()
{
    if( isEmpty() )
    {
        printf("Queue underflow\n");
        exit(1);
    }
    return rear->link->info;
}/* End of peek() */

int isEmpty()
{
    if( rear == NULL )
        return 1;
    else
        return 0;
}/*End of isEmpty()*/


void display()
{
    struct node *p;
    if(isEmpty())
    {
        printf("Queue is empty\n");
        return;
    }
    printf("Queue is :\n");
    p=rear->link;
    do
    {
        printf("%d ",p->info);
        p=p->link;
    }while(p!=rear->link);
    printf("\n");
}

Circular Queue

A circular queue is a Queue but a particular implementation of a queue. It is very efficient. It is also quite useful in low level code, because insertion and deletion are totally independant, which means that you don't have to worry about an interrupt handler trying to do an insertion at the same time as your main code is doing a deletion.

Algorithm for Insertion:-Step-1: If "rear" of the queue is pointing to the last position then go to step-2 or else step-3
Step-2: make the "rear" value as 0
Step-3: increment the "rear" value by one
Step-4:
  1. if the "front" points where "rear" is pointing and the queue holds a not NULL value for it, then its a "queue overflow" state, so quit; else go to step-4.2
  2. insert the new value for the queue position pointed by the "rear"
Algorithm for deletion:-
Step-1: If the queue is empty then say "empty queue" and quit; else continue
Step-2: Delete the "front" element
Step-3: If the "front" is pointing to the last position of the queue then step-4 else step-5
Step-4: Make the "front" point to the first position in the queue and quit
Step-5: Increment the "front" position by one

c program for tower of hanoic problem

TOWER OF HANOIC PROBLEM> (RECURSION)
#include<stdio.h>
void tofh(int ndisk, char source, char temp, char dest);

main( )
{
    char  source = 'A', temp = 'B', dest = 'C';
    int ndisk;
    printf("Enter the number of disks : ");
    scanf("%d", &ndisk );
    printf("Sequence is :\n");
    tofh(ndisk, source, temp, dest);
}/*End of main()*/

void tofh(int ndisk, char source, char temp, char dest)
{
    if(ndisk==1)
    {
        printf("Move Disk %d from %c-->%c\n", ndisk, source, dest);
        return;
    }
    tofh(ndisk-1, source, dest, temp);
    printf("Move Disk %d from %c-->%c\n", ndisk, source, dest);
    tofh(ndisk-1, temp, source, dest);

}

reference....

Recursive solution

Let call the three pegs Src (Source), Aux (Auxiliary) and Dst (Destination). To better understand and appreciate the following solution you should try solving the puzzle for small number of disks, say, 2,3, and, perhaps, 4. However one solves the problem, sooner or later the bottom disk will have to be moved from Src to Dst. At this point in time all the remaining disks will have to be stacked in decreasing size order on Aux. After moving the bottom disk from Src to Dst these disks will have to be moved from Aux to Dst. Therefore, for a given number N of disks, the problem appears to be solved if we know how to accomplish the following tasks:
  1. Move the top N - 1 disks from Src to Aux (using Dst as an intermediary peg)
  2. Move the bottom disk from Src to Dst
  3. Move N - 1 disks from Aux to Dst (using Src as an intermediary peg)
Assume there is a function Solve with four arguments - number of disks and three pegs (source, intermediary and destination - in this order). Then the body of the function might look like

Solve(N, Src, Aux, Dst)
    if N is 0 
      exit
    else
      Solve(N - 1, Src, Dst, Aux)
      Move from Src to Dst
      Solve(N - 1, Aux, Src, Dst)
This actually serves as the definition of the function Solve. The function is recursive in that it calls itself repeatedly with decreasing values of N until a terminating condition (in our case N = 0) has been met. To me the sheer simplicity of the solution is breathtaking. For N = 3 it translates into
  1. Move from Src to Dst.
  2. Move from Src to Aux.
  3. Move from Dst to Aux.
  4. Move from Src to Dst.
  5. Move from Aux to Src.
  6. Move from Aux to Dst.
  7. Move from Src to Dst.
Of course "Move" means moving the topmost disk. For N = 4 we get the following sequence
  1. Move from Src to Aux.
  2. Move from Src to Dst.
  3. Move from Aux to Dst.
  4. Move from Src to Aux.
  5. Move from Dst to Src.
  6. Move from Dst to Aux.
  7. Move from Src to Aux.
  8. Move from Src to Dst.
  9. Move from Aux to Dst.
  10. Move from Aux to Src.
  11. Move from Dst to Src.
  12. Move from Aux to Dst.
  13. Move from Src to Aux.
  14. Move from Src to Dst.
  15. Move from Aux to Dst.

c program to perform polynomial addition

polynomial addition using linked list

    #include<stdio.h>
    #include<malloc.h>
    #include<conio.h>
    struct link{
    int coeff;
    int pow;
    struct link *next;
    };
    struct link *poly1=NULL,*poly2=NULL,*poly=NULL;
    void create(struct link *node)
    {
    char ch;
    do
    {
    printf("\n enter coeff:");
    scanf("%d",&node->coeff);
    printf("\n enter power:");
    scanf("%d",&node->pow);
    node->next=(struct link*)malloc(sizeof(struct link));
    node=node->next;
    node->next=NULL;
    printf("\n continue(y/n):");
    ch=getch();
    }
    while(ch=='y' || ch=='Y');
    }
    void show(struct link *node)
    {
    while(node->next!=NULL)
    {
    printf("%dx^%d",node->coeff,node->pow);
    node=node->next;
    if(node->next!=NULL)
    printf("+");
    }
    }
    void polyadd(struct link *poly1,struct link *poly2,struct link *poly)
    {
    while(poly1->next && poly2->next)
    {
    if(poly1->pow>poly2->pow)
    {
    poly->pow=poly1->pow;
    poly->coeff=poly1->coeff;
    poly1=poly1->next;
    }
    else if(poly1->pow<poly2->pow)
    {
    poly->pow=poly2->pow;
    poly->coeff=poly2->coeff;
    poly2=poly2->next;
    }
    else
    {
    poly->pow=poly1->pow;
    poly->coeff=poly1->coeff+poly2->coeff;
    poly1=poly1->next;
    poly2=poly2->next;
    }
    poly->next=(struct link *)malloc(sizeof(struct link));
    poly=poly->next;
    poly->next=NULL;
    }
    while(poly1->next || poly2->next)
    {
    if(poly1->next)
    {
    poly->pow=poly1->pow;
    poly->coeff=poly1->coeff;
    poly1=poly1->next;
    }
    if(poly2->next)
    {
    poly->pow=poly2->pow;
    poly->coeff=poly2->coeff;
    poly2=poly2->next;
    }
    poly->next=(struct link *)malloc(sizeof(struct link));
    poly=poly->next;
    poly->next=NULL;
    }
    }
    main()
    {
    char ch;
    do{
    poly1=(struct link *)malloc(sizeof(struct link));
    poly2=(struct link *)malloc(sizeof(struct link));
    poly=(struct link *)malloc(sizeof(struct link));
    printf("\nenter 1st number:");
    create(poly1);
    printf("\nenter 2nd number:");
    create(poly2);
    printf("\n1st Number:");
    show(poly1);
    printf("\n2nd Number:");
    show(poly2);
    polyadd(poly1,poly2,poly);
    printf("\nAdded polynomial:");
    show(poly);
    printf("\n add two more numbers:");
    ch=getch();
    }
    while(ch=='y' || ch=='Y');
    }
coefficients Like-power terms are added in polynomial addition.
i.e.;
First Polynomial Second Polynomial
coeffcient of x + coeffcient of x
coeffcient of x^2 + coeffcient of x^2
coeffcient of x^3 + coeffcient of x^3
--------------------------------------…
and so on. If first polynomial is of 5th degree and second is of 3rd degree.
Then u add terms of both polynomial upto 3rd term and u put remaining 2 terms (4th and 5th) of first polynomial as it is in the final polynomial.

So ur logic goes like this.
u will have three linked lists
first linked list for first polynomial
second linked list for second polynomial
third linked list for addition of polynomials


u traverse linked list of higher-degree polynomial and keep on adding coefficients of both polynomials in a third polynomial.
after adding each coefficient u move to next node in both the linked lists.
during traversal lower degree polynomial will end then u simply copy remaining terms in third linked list.


Sunday, November 18, 2012

how to calculate the address of the 2D array

Address of a[ i ][ j ]th element (row major)
*********************************************
 BA + [ n * ( i - LBR) + ( j - LBC) ] * w

                                                         Where BA = Base address
                                                               W = Number of bytes occupied by each element
                                                                 N = Number of columns


Address of a[ i ][ j ]th element (colum major)
*********************************************
     BA + [ ( i - LBR) + m * ( j - LBC) ] * w

                                                           Where BA = Base address
                                                                        W = Number of bytes occupied by each element
                                                                         N = Number of rows

 WHAT IS A 2D ARRAY?

 A matrix (two dimensional array) is a group of lists, or arrays that are organized into one data set. To understand them, first look an example of the standard one dimensional array:

Array "A":
16
8
99
0
5

You can reference any point in the "array" by naming the array and following it with a number representing the position of a piece of data on the list. The first data on the array is represented with a "0", the second with a "1", and so on. For example, A[2] (in bold) represents 99 because it is the third figure of array A. You could imagine the references of the above table as the following:

Array "A":
[0]
[1]
[2]
[3]
[4]

A matrix is a set of arrays. Visualize the following table:

Matrix "B":
16 17 9
8 88 74
99 12 21
0 6 40
5 19 18

There are 3 different arrays in a single data set, "B". In Array A, you could reference any data by naming the point on the list, such as "1" or "3". However, with a matrix, you must give both a row and a column. You can reference data on a matrix in the following format:

MatrixName[row][column]

For example, B[3][2] would represent 40 because it is the it is on the fourth row down and the third column. Remember, matrix references also start at zero, not one! You can reference any of the data on this table with this chart:

Matrix "B":
[0][0] [0][1] [0][2]
[1][0] [1][1] [1][2]
[2][0] [2][1] [2][2]
[3][0] [3][1] [3][2]
[4][0] [4][1] [4][2]

Two-dimensional arrays are used everywhere, but are especially prevalent in computer programming and accounting

infix to postfix conversion

Infix to Postfix conversion using stack

Introduction:
         In the last post I have explained about the infix,prefix,postfix expression. In this post we are going to know about the conversion of infix to postfix expression.

Infix to Postfix Conversion:
  • Consider an infix string x+y*c.Each character of the string is called tokens.
  • The algorithm for converting an infix expression to postfix expression is given below.
  • We need a stack to solve this problem
Algorithm for converting infix expression to postfix expression:
  • Initialize an empty stack and a Postfix String S.
  • Read the tokens from the infix string one at a time from left to right
  • If the token is an operand, add it to the Postfix string S.
  • If the token is a left parentheses, Push it on to the stack
  • If the token is a right parentheses
    1. Repeatedly Pop the stack and add the poped out element in to the string S until a left parenthesis is encountered;
    2. Remove the left parenthesis from the stack and ignore it
  • If the token is an operator
    1. If the stack is empty push the operator in to the stack       
    2. If the stack is not empty compare the precedence of the operator with the element on top of the stack
      • If the operator in the stack has higher precedence than the token Pop the stack and add the poped out element in to the string S. else Push the operator in to the stack                   
      • Repeat this step until the stack is not empty or the operator in the stack has higher precedence than the token         
  • Repeat this step till all the characters are read.
  • After all the characters are read and the stack is not empty then Pop the stack and add the tokens to the string S
  • Return the Postfix string S
Example for Converting infix to Postfix Expression:

Example 1:
Infix String----->A*B+C/D
Solution:
  1. Initially the stack is empty and the Postfix String S has no characters
  2. Read the token A.A is a operand so it is added to the string S.now Stack->empty and S->A
  3. Read the token *.* is an operator.stack is empty so push * in to the stack. now Stack->* and S->A
  4. Read the token B.B is an operand so it is added to the string S. now Stack->* and S->AB
  5. Read the token +.+is an operator.compare +and *.* has higher precedence than +. so pop * from the stack and add it to the string S. now Stack->empty and S->AB*.now the stack is empty so push the + in to the stack.now Stack->+ and S->AB*
  6. Read the token C.C is a operand so it is added to the string S.now Stack->+ and S->AB*C
  7. Read the token /./ is an operator.compare /and +./ has higher precedence than +. so push / in to the stack . now Stack->+/ and S->AB*C
  8. Read the token D.D is a operand so it is added to the string S.now Stack->+/ and S->AB*CD
  9. All the characters are read but the stack is not empty so pop the stack and add the characters to the String. now S->AB*CD/+
     So the Postfix String is AB*CD/+


Example 2:
Infix String----->A*(B+C)/D
Solution:
  1. Initially the stack is empty and the Postfix String S has no character.
  2. Read the token A.A is a operand so it is added to the string S.now Stack->empty and S->A
  3. Read the token *.* is an operator.stack is empty so push * in to the stack. now Stack->* and S->A
  4. Read the token (.push the left parentheses in to the stack.
  5. Read the token B.B is an operand so it is added to the string S. now Stack->* and S->AB
  6. Read the token +.+is an operator.compare +and *.+ has lower precedence than *.So push + in to the stack. now Stack->*+ and S->AB
  7. Read the token C.C is an operand so it is added to the string S.now Stack->*+ and S->ABC
  8. Read the token ). ) is a right parentheses ,Pop the stack and add the + in to the string S. now Stack->* and S->ABC+
  9. Read the token /./ is an operator.compare /and *./ and * have equal precedence but * comes before /so pop the stack and add * in to the string S.now stack is empty so push / in to the stack . now Stack->/ and S->ABC+*
  10. Read the token D.D is an operand so it is added to the string S.now Stack->/ and S->ABC+*D 
  11. Now the input string is empty but the stack is not empty so pop the stack and add the characters to the String.now Stack->Empty and S->ABC+*D/
         So the Postfix String is ABC+*D/


program to perform sparse matrix addition

program to add sparse matrix

#include <stdio.h>
#include <conio.h>
#include <alloc.h>
#define MAX1 3
#define MAX2 3
#define MAXSIZE 9
#define BIGNUM 100
struct sparse
{
int *sp ;
int row ;
int *result ;
} ;
void initsparse ( struct sparse * ) ;
void create_array ( struct sparse * ) ;
int count ( struct sparse ) ;
void display ( struct sparse ) ;
void create_tuple ( struct sparse *, struct sparse ) ;
void display_tuple ( struct sparse ) ;
void addmat ( struct sparse *, struct sparse, struct sparse ) ;
void display_result ( struct sparse ) ;
void delsparse ( struct sparse * ) ;
void main( )
{
struct sparse s[5] ;
int i ;
clrscr( ) ;
for ( i = 0 ; i <= 4 ; i++ )
initsparse ( &s[i] ) ;
create_array ( &s[0] ) ;
create_tuple ( &s[1], s[0] ) ;
display_tuple ( s[1] ) ;
create_array ( &s[2] ) ;
create_tuple ( &s[3], s[2] ) ;
display_tuple ( s[3] ) ;
addmat ( &s[4], s[1], s[3] ) ;
printf ( "\nResult of addition of two matrices: " ) ;
display_result ( s[4] ) ;
for ( i = 0 ; i <= 4 ; i++ )
delsparse ( &s[i] ) ;
getch( ) ;
}
/* initialises structure elements */
void initsparse ( struct sparse *p )
{
p -> sp = NULL ;
p -> result = NULL ;
}
/* dynamically creates the matrix */
void create_array ( struct sparse *p )
{
int n, i ;
/* allocate memory */
p -> sp = ( int * ) malloc ( MAX1 * MAX2 * sizeof ( int ) ) ;
/* add elements to the array */
for ( i = 0 ; i < MAX1 * MAX2 ; i++ )
{
printf ( "Enter element no. %d:", i ) ;
scanf ( "%d", &n ) ;
* ( p -> sp + i ) = n ;
}
}
/* displays the contents of the matrix */
void display ( struct sparse s )
{
int i ;
/* traverses the entire matrix */
for ( i = 0 ; i < MAX1 * MAX2 ; i++ )
{
/* positions the cursor to the new line for every new row */
if ( i % MAX2 == 0 )
printf ( "\n" ) ;
printf ( "%d\t", * ( s.sp + i ) ) ;
}
}
/* counts the number of non-zero elements */
int count ( struct sparse s )
{
int cnt = 0, i ;
for ( i = 0 ; i < MAX1 * MAX2 ; i++ )
{
if ( * ( s.sp + i ) != 0 )
cnt++ ;
}
return cnt ;
}
/* creates an array that stores information about non-zero elements */
void create_tuple ( struct sparse *p, struct sparse s )
{
int r = 0 , c = -1, l = -1, i ;
/* get the total number of non-zero elements
and add 1 to store total no. of rows, cols, and non-zero values */
p -> row = count ( s ) + 1 ;
/* allocate memory */
p -> sp = ( int * ) malloc ( p -> row * 3 * sizeof ( int ) ) ;
/* store information about
total no. of rows, cols, and non-zero values */
* ( p -> sp + 0 ) = MAX1 ;
* ( p -> sp + 1 ) = MAX2 ;
* ( p -> sp + 2 ) = p -> row - 1 ;
l = 2 ;
/* scan the array and store info. about non-zero values in the 3-tuple */
for ( i = 0 ; i < MAX1 * MAX2 ; i++ )
{
c++ ;
/* sets the row and column values */
if ( ( ( i % MAX2 ) == 0 ) && ( i != 0 ) )
{
r++ ;
c = 0 ;
}
/* checks for non-zero element row, column and non-zero element value is assigned to the matrix */
if ( * ( s.sp + i ) != 0 )
{
l++ ;
* ( p -> sp + l ) = r ;
l++ ;
* ( p -> sp + l ) = c ;
l++ ;
* ( p -> sp + l ) = * ( s.sp + i ) ;
}
}
}
/* displays the contents of the matrix */
void display_tuple ( struct sparse s )
{
int i, j ;
/* traverses the entire matrix */
printf ( "\nElements in a 3-tuple: \n" ) ;
j = ( * ( s.sp + 2 ) * 3 ) + 3 ;
for ( i = 0 ; i < j ; i++ )
{
/* positions the cursor to the new line for every new row */
if ( i % 3 == 0 )
printf ( "\n" ) ;
printf ( "%d\t", * ( s.sp + i ) ) ;
}
printf ( "\n" ) ;
}
/* carries out addition of two matrices */
void addmat ( struct sparse *p, struct sparse s1, struct sparse s2 )
{
int i = 1, j = 1, k = 1 ;
int elem = 1 ;
int max, amax, bmax ;
int rowa, rowb, cola, colb, vala, valb ;
/* get the total number of non-zero values from both the matrices */
amax = * ( s1.sp + 2 ) ;
bmax = * ( s2.sp + 2 ) ;
max = amax + bmax ;
/* allocate memory for result */
p -> result = ( int * ) malloc ( MAXSIZE * 3 * sizeof ( int ) ) ;
while ( elem <= max )
{
/* check if i < max. non-zero values
in first 3-tuple and get the values */
if ( i <= amax )
{
rowa = * ( s1.sp + i * 3 + 0 ) ;
cola = * ( s1.sp + i * 3 + 1 ) ;
vala = * ( s1.sp + i * 3 + 2 ) ;
}
else
rowa = cola = BIGNUM ;
/* check if j < max. non-zero values in secon 3-tuple and get the values */
if ( j <= bmax )
{
rowb = * ( s2.sp + j * 3 + 0 ) ;
colb = * ( s2.sp + j * 3 + 1 ) ;
valb = * ( s2.sp + j * 3 + 2 ) ;
}
else
rowb = colb = BIGNUM ;
/* if row no. of both 3-tuple are same */
if ( rowa == rowb )
{
/* if col no. of both 3-tuple are same */
if ( cola == colb )
{
/* add tow non-zero values
store in result */
* ( p -> result + k * 3 + 0 ) = rowa ;
* ( p -> result + k * 3 + 1 ) = cola ;
* ( p -> result + k * 3 + 2 ) = vala + valb ;
i++ ;
j++ ;
max-- ;
}
/* if col no. of first 3-tuple is < col no. of second 3-tuple, then add info. as it is to result */
if ( cola < colb )
{
* ( p -> result + k * 3 + 0 ) = rowa ;
* ( p -> result + k * 3 + 1 ) = cola ;
* ( p -> result + k * 3 + 2 ) = vala ;
i++ ;
}
/* if col no. of first 3-tuple is > col no. of second 3-tuple, then add info. as it is to result */
if ( cola > colb )
{
* ( p -> result + k * 3 + 0 ) = rowb ;
* ( p -> result + k * 3 + 1 ) = colb ;
* ( p -> result + k * 3 + 2 ) = valb ;
j++ ;
}
k++ ;
}
/* if row no. of first 3-tuple is < row no. of second 3-tuple, then add info. as it is to result */
if ( rowa < rowb )
{
* ( p -> result + k * 3 + 0 ) = rowa ;
* ( p -> result + k * 3 + 1 ) = cola ;
* ( p -> result + k * 3 + 2 ) = vala ;
i++ ;
k++ ;
}
/* if row no. of first 3-tuple is > row no. of second 3-tuple, then add info. as it is to result */
if ( rowa > rowb )
{
* ( p -> result + k * 3 + 0 ) = rowb ;
* ( p -> result + k * 3 + 1 ) = colb ;
* ( p -> result + k * 3 + 2 ) = valb ;
j++ ;
k++ ;
}
elem++ ;
}
/* add info about the total no. of rows, cols, and non-zero values that the resultant array contains to the result */
* ( p -> result + 0 ) = MAX1 ;
* ( p -> result + 1 ) = MAX2 ;
* ( p -> result + 2 ) = max ;
}
/* displays the contents of the matrix */
void display_result ( struct sparse s )
{
int i ;
/* traverses the entire matrix */
for ( i = 0 ; i < ( * ( s.result + 0 + 2 ) + 1 ) * 3 ; i++ )
{
/* positions the cursor to the new line for every new row */
if ( i % 3 == 0 )
printf ( "\n" ) ;
printf ( "%d\t", * ( s.result + i ) ) ;
}
}
/* deallocates memory */
void delsparse ( struct sparse *p )
{
if ( p -> sp != NULL )
free ( p -> sp ) ;
if ( p -> result != NULL )
free ( p -> result ) ;
}

Sparse matrices, which are common in scientific applications, are matrices in which most elements are zero. To save space and running time it is critical to only store the nonzero elements. A standard representation of sparse matrices in sequential languages is to use an array with one element per row each of which contains a linked-list of the nonzero values in that row along with their column number. A similar representation can be used in parallel. In NESL a sparse matrix can be represented as a sequence of rows, each of which is a sequence of (column-number, value) pairs of the nonzero values in the row

Wednesday, November 7, 2012

operator overloading using friend function

operator overloading both unary and binary operator using friend function.


What is a friend function c plus plus?

A friend function in C++ is a function that is not part of the implementation of a class, i.e. not a method of the class, but that is allowed to manipulate the private parts of a class.

#include <iostream>
using namespace std;
class loc {
int longitude, latitude;
public:
loc() {} // needed to construct temporaries
loc(int lg, int lt) {
longitude = lg;
latitude = lt;
}
void show() {
cout << longitude << " ";
cout << latitude << "\n";
}
friend loc operator+(loc , loc ); // now a friend
loc operator-(loc op2);
loc operator=(loc op2);
loc operator++();
};
// Now, + is overloaded using friend function.
loc operator+(loc op1, loc op2)
{
loc temp;
temp.longitude = op1.longitude + op2.longitude;
temp.latitude = op1.latitude + op2.latitude;
return *this;
}
// Overload - for loc.
loc loc::operator-(loc op2)
{
loc temp;
// notice order of operands
temp.longitude = longitude - op2.longitude;
temp.latitude = latitude - op2.latitude;
return temp;
}
// Overload assignment for loc
loc loc::operator=(loc op2)
{
longitude = op2.longitude;
latitude = op2.latitude;
return *this; // i.e., return object that generated call
}
// Overload ++ for loc.
loc loc::operator++()
{
longitude++;
latitude++;
return *this;
}
int main()
{
loc ob1(10, 20), ob2( 5, 30);
ob1 = ob1 + ob2;
ob1.show();
return 0;
}


C++ Operator Overloading Guidelines

One of the nice features of C++ is that you can give special meanings to operators, when they are used with user-defined classes. This is called operator overloading. You can implement C++ operator overloads by providing special member-functions on your classes that follow a particular naming convention. For example, to overload the + operator for your class, you would provide a member-function named operator+ on your class.
The following set of operators is commonly overloaded for user-defined classes:
  • = (assignment operator)
  • + - * (binary arithmetic operators)
  • += -= *= (compound assignment operators)
  • == != (comparison operators)

operator overloading

operator overloading using unary and binary operator
#include <iostream>
using namespace std;
class loc
{
int longitude, latitude;
public:
loc() {} // needed to construct temporaries
loc(int lg, int lt)
{
longitude = lg;
latitude = lt;
}
void show()
{
cout << longitude << " ";
cout << latitude << "\n";
}
loc operator+(loc op2);
loc operator-(loc op2);
loc operator=(loc op2);
loc operator++();
};
// Overload + for loc.
loc loc::operator+(loc op2)
{
loc temp;
temp.longitude = op2.longitude + longitude;
temp.latitude = op2.latitude + latitude;
return *this;
}
// Overload - for loc.
loc loc::operator-(loc op2)
{
loc temp;
// notice order of operands
temp.longitude = longitude - op2.longitude;
temp.latitude = latitude - op2.latitude;
return *this;
}
// Overload asignment for loc.
loc loc::operator=(loc op2)
{
longitude = op2.longitude;
latitude = op2.latitude;
return *this; // i.e., return object that generated call
}
// Overload prefix ++ for loc.
loc loc::operator++()
{
longitude++;
latitude++;
return *this;
}
int main()
{
loc ob1(10, 20), ob2( 5, 30), ob3(90, 90);
ob1.show();
ob2.show();
++ob1;
ob1.show(); // displays 11 21
ob2 = ++ob1;
ob1.show(); // displays 12 22
ob2.show(); // displays 12 22
ob1 = ob2 = ob3; // multiple assignment
ob1.show(); // displays 90 90
ob2.show(); // displays 90 90
return 0;
}

*what is operator overloading?
Operators are functions. Specifically, operators are special functions that are used to perform operations on data without directly calling methods each time. Common operators that you should be familiar with include +, -, *, /, <<, >>, and so on. All such operators can be used on primative data types in C++ to achieve certain results. For example, we can use the + operator to add together two numeric values, such as ints, floats, and doubles:
* What are the benefits of operator overloading?
By overloading standard operators on a class, you can exploit the intuition of the users of that class. This lets users program in the language of the problem domain rather than in the language of the machine.
The ultimate goal is to reduce both the learning curve and the defect rate.