C++ Program to demonstrate overloading of pre-increment operator [DEVCPP/GCC]

PROGRAM

//Program to demonstrate overloading of pre-increment operator

# include <iostream>

using namespace std;

class complex
{
int real,imag;

     public:

     complex()
{
real=0;imag=0;
}

     complex(int x,int y)
{
real=x;imag=y;
}

void show()
{
cout<<"Complex number is:"<<real<<"+"<<imag<<"i";
}

      complex operator++()      //operator overloading code
{                                    
complex temp;
temp.real= ++real;      
temp.imag= ++imag;
return temp;
}
};

int main()
{
complex c1(1,2),c3;
c3=++c1;     //c1.operator++()
c3.show();
return 0;
}

OUTPUT


C++ Program to demonstrate binary operator overloading [DEVCPP/GCC]

We have already discussed about Operator Overloading in C++ in our previous post: http://techcpp.blogspot.com/2017/07/operator-overloading.html. Here is a simple program on it.

PROGRAM

//Program to demonstrate operator (Binary +) overloading 

# include <iostream>
using namespace std;

class complex
{
int real,imag;

public:

complex()
{
real=0;
          imag=0;
}
complex( int x,int y )
{
real=x;
          imag=y;
}

    complex operator + (complex c)  
{                                                   
complex temp;
temp.real= real+c.real;    
temp.imag= imag+c.imag;
return temp;
}

void show()
{
cout<<"Complex number is:"<<real<<"+"<<imag<<"i";
}
};

int main()
{
complex c1(1,2),c2(2,3),c3;
c3=c1+c2;                                          //c1.operator+(c2)
c3.show();
return 0;
}

OUTPUT


C++ Functions

FUNCTIONS
Functions allow to structure programs in segments of code to perform individual tasks. Functions are used to provide modularity to a program. There are two types of functions in programming Languages i.e. Standard Library Functions and User Defined Functions.
Standard Library Functions
These are built-in functions that are defined in the libraries of programming language. These are used to perform basic operations like input(scanf() ,gets()), output(printf(),puts()), mathematical operations(sqrt()), string related operations etc.
These functions are limited and thus can not be used to perform user specific tasks.
User Defined Functions
As the name implies, these are block of code defined by user as per his/her requirements. These are basically modules which facilitate programming. For instance, if you wish to make a program for mini calculator, you can have various user defined functions as add(), subtract(), multiply(), divide() etc. and call those any number of times you want.

PARTS OF A FUNCTION

The general syntax of a function in C++ is

return_type function_name (Argument_List)
{
        //Body of function

FUNCTION DECLARATION/PROTOTYPE

In C++, identifiers can only be used in expressions if they have been declared before. Thus, functions cannot be called before they are declared. If a user wants to call the function before the body of function is defined, the user needs to declare the prototype of function containing necessary details of function.

Declaring a function is important as compiler does not know about the user defined function in advance. A Function declaration does not contain body of function. The general syntax of Function Declaration is

return_type function_name (Argument_List);

FUNCTION CALL

When a program calls a function, program control is transferred to the called function. A called function performs defined task and when its return statement is executed or when its function-ending closing brace is reached, it returns program control back to the main program.


C++ Operator Overloading

OPERATOR OVERLOADING

When an operator is overloaded with multiple jobs it is known as Operator Overloading. It is one of the methods to implement compile time polymorphism.

Operators are overloaded so that they can perform special operations relative to the classes. When an operator is overloaded, none of its original meaning is lost, instead, the types of object it can be applied to is expanded. By overloading operators, we can use objects of classes in expressions in the same way as we use C++ built in data types.

RULES

Any symbol can be used as a function name.
  • If it is a valid operator in C language.
  • If it is preceded by 'operator' keyword.

Operators that can't be overloaded are 'sizeof' and '?:

TYPES

There are two types of Operator Overloading.
  • Unary Operator Overloading.
  • Binary Operator Overloading.

WHY OPERATOR OVERLOADING
  •  It makes the code readable.
  •  Extention of language to include user defined types i.e classes.
  • Makes operator sensitive to context.
  • Generalization of function overloading.

SYNTAX




C++ Program to illustrate classes and objects

We have already discussed the concept of classes and objects: https://techcpp.blogspot.in/2017/07/c-classes-and-objects.html.

Lets understand a simple program implementing that concept. The program below contains a class Box which can be used to create multiple boxes. The properties of Box are its Length, Width and Height. The member functions used are setDimensions() used to set length, width and height of the box and getVolume() used to obtain volume of the box. 

Two objects of this class is created in the main function and respective volumes are obtained by setting their dimensions.

PROGRAM

//Program to illustrate Object and classes

#include <iostream>

using namespace std;

class Box
{
        // Data Members

        float length;
        float width;
        float height;

        // Member Functions

        public:

        void setDimensions(float l, float w, float h)
        {
                length = l;
                width = w;
                height = h;
        }

        float getVolume()
        {
                return (length * width * height);
        }

};

int main()
{
        Box b1, b2;

        b1.setDimensions(10,20,30);
        cout<<"\nVOLUME OF BOX 1: "<<b1.getVolume();

        b2.setDimensions(5,25,15);
        cout<<"\nVOLUME OF BOX 2: "<<b2.getVolume();

        return 0;
}

OUTPUT

C++ Program to illustrate classes and objects


C++ Classes and Objects

C++ supports object oriented programming. Object-oriented programming is based on the concept of classes and objects. The use of classes and objects makes it easier to build and design applications and shows close resemblance to the real world.

WHAT IS CLASS?
  • It is a user defined data type which serves as a blueprint for an object. 
  • It is a logical entity i.e. no storage is assigned when we define a class.
  • A single class can be used to create multiple objects.
  • A class describes the contents of the objects that belong to it.

WHAT IS OBJECT?
  • An object is an instance of a class.
  • An object is the actual component of program i.e. storage is assigned when we create an object.
  • It is an entity having some characteristics and behavior.
  • An object’s properties are what it knows and its methods are what it can do. 
  • Objects are the fundamental building blocks of applications from an object-oriented perspective.

EXAMPLE

The concept of classes and objects can be understood by the following example:

Human Beings have certain properties and behavior. Each person differs from the other on the basis of one or more properties like name, age, gender, height, weight etc. Thus, we all share certain properties and are distinguished based on them.

Let us define a class named HumanBeing

class HumanBeing
{
          string name;
          int age;
          char gender;
          float height;
          float weight;
};

All Human Beings share common behavior such as breathing, eating, drinking etc. Though Human Beings can be distinguished by their set of properties; but all of them breathe, drink and eat. Thus, all the objects of the same class have the same behavior.

Lets redefine our class adding some behavior,

class HumanBeing
{
          //Properties or Data Members

          string name;
          int age;
          char gender;
          float height;
          float weight;

          // Behavior or Member Functions

          Breathe();
          Eat();
          Drink();
};

Once we have defined a class, we can define as many objects as required. Each object will possess some properties and behavior. The properties of objects may be same or different depending upon the context.

HumanBeing Alice, Bob, Steve;

Here Alice, Bob and Steve are objects of HumanBeing class. Each of them possess a set of properties and common behavior or methods.


C++ Program to solve Tower of Hanoi

TOWER OF HANOI

Tower of Hanoi is a famous mathematical puzzle. It was proposed by Edouard Lucas in 1883. The objective of this puzzle is to move stack of n disks from one rod to another considering the following rules:

1) Only one disk can be moved at a time.
2) A bigger disk can not be placed on the top of a smaller disk.
3) Only the topmost disk can be moved from the stack.

The Tower of Hanoi problem takes minimum (2^n)-1 moves to solve.

TOWER OF HANOI WITH ONE DISK



TOWER OF HANOI WITH TWO DISKS





TOWER OF HANOI WITH THREE DISKS









PROGRAM

//Program to solve Tower of Hanoi Problem

#include <iostream>

using namespace std;

void toh(int n, char from, char to, char aux)
{
        if(n==1)
        {
                 cout<<"\nMOVE DISK FROM TOWER "<<from<<" TO TOWER "<<to; 
        }
        else
        {
                toh(n-1,from,aux,to);
                cout<<"\nMOVE DISK FROM TOWER "<<from<<" TO TOWER "<<to;
                toh(n-1,aux,to,from);
        }
}

int main()
{
        int n;
        cout<<"ENTER NUMBER OF DISKS: ";
        cin>>n;
        toh(n,'A','C','B');
        return 0;
}

OUTPUT




C++ Program to convert octal number to its decimal equivalent [DEVCPP/GCC]

PROGRAM

//Program to covert octal to decimal equivalent.

# include <iostream>
# include <cmath>

using namespace std;

int main()
{
int octaltodecimal(int);
int num;
cout<<"ENTER A NUMBER(OCTAL):"<<endl;
cin>>num;

cout<<"DECIMAL EQUIVALENT IS:"<<octaltodecimal(num);
}

int octaltodecimal(int num)
{
int count=0,i,n,l,m,sum=0;
n=num;
while(num)
{
num=num/10;
count++;
}
m=count;
while(n)
{
l=n%10;
sum=sum+(l*pow(8,count-m));
m--;
n=n/10;
}
return sum;
}

OUTPUT






C++ Program to display alphanumeric triangle [DEVCPP/GCC]

OBJECTIVE

We intend to make a program which accepts the number of rows from user and display a triangular pattern like below:

1
a b
2 3 4
c d e f
5 6 7 8 9

PROGRAM

// Program to display alphanumeric triangle

#include <iostream>

using namespace std;

int main()
{
        int n,i,j,k=1;
        char ch='a';

        cout<<"\nENTER NUMBER OF ROWS: ";
        cin>>n;

        for(i=1;i<=n;i++)
       {
                for(j=1;j<=i;j++)
                {
                        if(i%2)
                        {
                                cout<<k<<" ";
                                k++;
                        }
                        else
                        {
                               cout<<ch<<" ";
                               ch++;
                        }
               }
               cout<<endl;
       }

       return 0;
}

OUTPUT


C++ Program to shuffle elements in pairs [DEVCPP/GCC]

OBJECTIVE

We have to shuffle the elements of an array such that each element, starting from the beginning of array is interchanged with its successor element.


PROGRAM

// C++ Program to shuffle elements in pairs

#include <iostream>
#define N 10

using namespace std;

int main()
{
        int i,temp,list[N];

        cout<<"ENTER ELEMENTS \n";

        for( i=0 ; i<N ; i++ )
        {
                   cin>>list[i];
        }

        for( i=0 ; i<N ; i=i+2 )
        {
                  temp = list[i];
                  list[i] = list[i+1];
                  list[i+1]=temp;
        }

        cout<<"\nSHUFFLED ELEMENTS \n";

        for( i=0 ; i<N ; i++ )
        {
                  cout<<list[i]<<" ";
        }

        return 0;
}

OUTPUT


C++ Program to design a Magic Square [DEVCPP/GCC]

PROGRAM

//Program to design a Magic Square.

#include<iostream>
using namespace std;

int main()
{
int k[4][4],i,j,a,b,c,d,p,h;
int sum1,sum2,sum3,sum4;
char ch='n';

     cout<<"ENTER THE VALUES OF a,b,c,d"<<endl;
cout<<"a:";
cin>>a;
cout<<"\nb:";
cin>>b;
cout<<"\nc:";
cin>>c;
cout<<"\nd:";
cin>>d;

     cout<<"\nSUM OF ELEMENTS ENTERED(a,b,c,d):"<<(a+b+c+d)<<endl;
cout<<"DESIGNED A MAGICAL SQUARE USING THE ENTERED NUMBERS(a,b,c,d)..." <<endl<<endl;

    k[0][0]=a;    k[0][1]=b;    k[0][2]=c;    k[0][3]=d;
k[1][0]=d+1;  k[1][1]=c-1;  k[1][2]=b-3;  k[1][3]=a+3;
k[2][0]=b-2;  k[2][1]=a+2;  k[2][2]=d+2;  k[2][3]=c-2;
k[3][0]=c+1;  k[3][1]=d-1;  k[3][2]=a+1;  k[3][3]=b-1;    //Formula for magic square
for(i=0;i<4;i++)
{
for(j=0;j<4;j++)
{
cout<<k[i][j]<<"\t";
}
cout<<endl;
    }
   
 
     cout<<"\nTHIS IS THE MAGICAL SQUARE\n"<<endl;
     cout<<"IN THIS MAGICAL SQUARE THE SUM OF ELEMENTS OF EACH ROW\n"<<endl;
     cout<<"THE SUM OF ELEMENTS OF EACH COLUMN\n"<<endl;
     cout<<"THE SUM OF ELEMENTS OF EACH DIAGONAL\n"<<endl;
     cout<<"THE SUM OF ELEMENTS OF MIDDLE SQUARE\n"<<endl;
     cout<<"WILL BE SAME. AND IT IS EQUAL TO THE SUM OF THE ELEMENTS ENTERED."<<endl<<endl;
     cout<<"LET US SEE..."<<endl;
     cout<<"FROM WHERE U WANNA START:\n\n";
 
     do
     {
   
             cout<<"1.ROWS\n";
             cout<<"2.COLUMNS\n";
             cout<<"3.DIAGONALS\n";
             cout<<"4.MIDDLE SQUARE\n";
             cout<<"ENTER YOUR CHOICE:\n";
             cin>>h;
 
             switch(h)
             {
   
                   case 1:
   
do
{
                          cout<<"ROWS\n";
                          cout<<"WE HAVE 4 ROWS 1,2,3,4. ENTER THE NO OF ROW WHOSE SUM OF ELEMENTS U WANT TO SEE\n";
                          cin>>p;
   
                           switch(p)
    {
   
                                 case 1:

                                 i=0; sum1=0;
                               for(j=0;j<4;j++)
  {
  sum1=sum1+k[i][j];
}
cout<<"SUM OF ELEMENTS OF 1ST ROW:"<<sum1<<endl;
break;
case 2:

                                 i=1; sum2=0;
                               for(j=0;j<4;j++)
  {
  sum2=sum2+k[i][j];
}
cout<<"SUM OF ELEMENTS OF 2ND ROW:"<<sum2<<endl;
break;
case 3:

                                  i=2; sum3=0;
                                for(j=0;j<4;j++)
  {
  sum3=sum3+k[i][j];
}
cout<<"SUM OF ELEMENTS OF 3RD ROW:"<<sum3<<endl;
break;
                                 case 4:
   
                                   i=3; sum4=0;
                                 for(j=0;j<4;j++)
  {
  sum4=sum4+k[i][j];
}
cout<<"SUM OF ELEMENTS OF 4Th ROW:"<<sum4<<endl;
break;
default :
cout<<"default";
break;
   }

cout<<"DO U WISH TO CONTINUE WITH OTHER ROWS:"<<endl;
cin>>ch;
   
    }while(ch=='Y'||ch=='y');
break;
case 2:
do
{
cout<<"COLUMNS"<<endl;
cout<<"WE HAVE 4 COLUMNS 1,2,3,4. ENTER THE NO OF COLUMN WHOSE SUM OF ELEMENTS YOU WANT TO SEE\n";
cin>>p;

              switch(p)
{
case 1:

                    j=0; sum1=0;
for(i=0;i<4;i++)
{
sum1=k[i][j]+sum1;
}
cout<<"SUM OF ELEMENT OF 1ST COLUMN:"<<sum1<<endl;
break;
case 2:

                     j=1; sum2=0;
for(i=0;i<4;i++)
{
sum2=k[i][j]+sum2;
}
cout<<"SUM OF ELEMENT OF 2ND COLUMN:"<<sum2<<endl;
break;
case 3:

                     j=2; sum3=0;
for(i=0;i<4;i++)
{
sum3=k[i][j]+sum3;
}
cout<<"SUM OF ELEMENT OF 3RD COLUMN:"<<sum3<<endl;
break;
case 4:

                      j=3; sum4=0;
for(i=0;i<4;i++)
{
sum4=k[i][j]+sum4;
}
cout<<"SUM OF ELEMENT OF 4TH COLUMN:"<<sum4<<endl;
break;
default:
cout<<"default";
break;
}
cout<<"DO YOU WISH TO CONTINUE WITH COLUMNS... "<<endl;
cin>>ch;

  }while(ch=='Y'||ch=='y');
break;
case 3:
do
{

                cout<<"DIAGONALS"<<endl;
cout<<"WE HAVE TWO DIAGONALS 1,2.ENTER THE DIADONAL WHOSE SUM OF ELEMENTS YOU WANT TO SEE\n";
cin>>p;

                switch(p)
{

                       case 1:

                       sum1=0;
for(i=0,j=0;i<4;i++,j++)
{
sum1=sum1+k[i][j];
}
cout<<"SUM OF ELEMENTS OF 1ST DIAGONAL:"<<sum1<<endl;
break;
case 2:

                        sum2=0;
for(i=0,j=3;i<4;i++,j--)
{
sum2=sum2+k[i][j];
}
cout<<"SUM OF ELEMENTS OF 1ST DIAGONAL:"<<sum2<<endl;
break;
default :
cout<<"DEFAULT";
break;
}
cout<<"DO WISH TO CONTINUE WITH ANOTHER DIAGONAL..."<<endl;
cin>>ch;

  }while(ch=='Y'||ch=='y');
break;
case 4:

          sum1=0;
cout<<"MIDDLE INNER SQUARE";

          for(i=1;i<3;i++)
{
for(j=1;j<3;j++)
{
sum1=sum1+k[i][j];
}
}
cout<<"SUM OF ELEMENTS OF MIDDLE SQUARE IS:"<<sum1<<endl;
break;
      }
      cout<<"DO YOU HAVE SOME OTHER CHOICE:"<<endl;
      cin>>ch;
}
while(ch=='Y'||ch=='y');

}

OUTPUT




   

C/C++ Program to create a Linked List [DEVCPP/GCC]

PROGRAM

//Program to create a Linked List and to insert and delete elements by value

#include <iostream>
#include <cstdlib>

using namespace std;

struct node
{
int val;
struct node *next;
};

struct node *temp,*stemp,*ttemp,*first;

void Insert(int item)
{
temp= new node;
temp->val = item ;
temp->next= NULL ;

if(first==NULL)
{
first=temp;
}
else
{
stemp = first;
while(stemp->next!=NULL)
{
stemp=stemp->next;
}
stemp->next=temp;
}
cout<<"\nELEMENT INSERTED: "<<item;
}

void Delete(int item)
{
bool found=false;

if(first==NULL)
{
cout<<"\nLINKED LIST IS EMPTY!";
}
else
{
ttemp=stemp=first;
while(stemp->next!=NULL)
{
if(stemp->val==item)
{
found=true;
break;
}
ttemp=stemp;
stemp=stemp->next;
}

if(found)
{
if(stemp->next != NULL)
{
ttemp->next=stemp->next;
stemp->next=NULL;
}
else
{
ttemp->next=NULL;
stemp->next=NULL;
}
delete stemp;

cout<<"\nELEMENT DELETED!";
}
else
{
cout<<"\nELEMENT NOT FOUND!";
}
}
}

void Display()
{
if(first==NULL)
{
cout<<"\nLINKED LIST IS EMPTY\n";
}
else
{
stemp = first;
cout<<"\n\nLINKED LIST\n";

                    while(stemp!=NULL)
{
cout<<stemp->val<<" ";
stemp=stemp->next;
}
cout<<endl;
}
}

int main()
{
Insert(1);
Insert(2);
Insert(3);

  Display();

Delete(2);
Display();

Insert(5);
Display();

return 0;
}

OUTPUT


C++ Program to sort elements using Quick Sort [DEVCPP/GCC]

QUICK SORT

It is also called Partition Exchange sort. As the name suggests Quick Sort sorts very quickly. When implemented in a proper way, it can be two or three times faster than its competitors mergesort and heapsortIt is based on the rule of Divide and Conquer. It was developed by Tony Hoare in 1959.

This algorithm divides the list into 3 parts:

1. Elements less than the pivot element.
2. Pivot element.
3. Elements greater than the pivot element.

Pivot (Special value) may be the first, middle or last element, pivot divides the array into two parts after each pass, values on the left hand side of pivot are less or equal to pivot and those on the right hand side are greater than the pivot value.

EXAMPLE

PROGRAM

#include <iostream>

using namespace std;

void Quick_sort(int a[], int lb, int ub)
{
                int L,R,X,temp; 
   
                if(lb>=ub)
                    return; 
                               
                L=lb;
                R=ub;
                X=a[lb]; 
               
                while(L<R)
                {
               
                    while(a[L]<=X && L<R)
                                    ++L;
                               
                     while(a[R]>X)
                                    --R; 
                                               
                      if(L<R)
                      {
                             temp=a[L];
                             a[L]=a[R];
                             a[R]=temp;
                       } 
                }        
               
                a[lb]=a[R];
                a[R]=X; 
               
                Quick_sort(a,lb,R-1);
                Quick_sort(a,R+1,ub);
}

int main()
{
                int a[10],i;
                cout<<"ENTER THE ELEMENTS:\n";
               
                for(i=0;i<10;i++)
                {
                    cin>>a[i];
                } 
               
                Quick_sort(a,0,9);
               
                cout<<"SORTED ELEMENTS:\n"; 
               
                for(i=0;i<10;i++)
                {
                    cout<<a[i]<<" ";
                } 

}

OUTPUT



FIND US ON FACEBOOK!