OOPc using C++

With this blog I want to share my knowledge of OOPs and C++. I Hope this can quench your thirst for learning.Any suggestions and comments are welcome.

Monday, August 23, 2010

Program 13 - C++ program to illustrate the usage of this pointer

/*C++ program to illustrate the usage of this pointer*/
#include<iostream.h>
#include<conio.h>
#include<string.h>

class person
{
       char name[20];
       float age;
public:
      person(char *s,float a)
     {
             strcpy(name,s);
             age=a;
       }
     person &person::greater(person &x)
    {
           if(x.age>=age)
                 return x;
          else
                 return *this;
     }
   void display()
   {
          cout<<"Name: "<<name<<"\nAge: "<<age<<endl;
     }
};
void main()
{
     clrscr();
     person p1("John",37.50),p2("Ahmed",29.0),p3("Heffer",40.25);
     person p=p1.greater(p3);
     cout<<"Elder person is:\n";
     p.display();
     p=p1.greater(p2);
     cout<<"Elder person is\n";
     p.display();
   
    getch();
}

OUTPUT:
Elder person is:
Name: Heffer
Age: 40.25
Elder person is
Name: John
Age: 37.5

Program 12 - C++ program to perform arithmetic operations on complex numbers using operator overloading

/*C++ program to perform arithmetic operations on complex numbers using operator overloading*/
#include<iostream.h>
#include<conio.h>
class complex
{
          float x,y;
          public:
              complex() {}
              complex(float real,float img)
               {
                       x=real; y=img;
                }
complex operator+(complex);
complex operator-(complex);
complex operator*(complex);
void operator/(complex);
void display()
{
        cout<<x<<" + "<<y<<"i"<<endl;
}
};
complex complex::operator+(complex c)
{
         complex temp;
         temp.x=x+c.x;
         temp.y=y+c.y;
         return(temp);
}
complex complex::operator-(complex d)
{
         complex temp;
         temp.x=x-d.x;
         temp.y=y-d.y;
         return(temp);
}
complex complex::operator*(complex e)
{
        complex temp;
        temp.x=x*e.x+y*e.y*(-1);
        temp.y=x*e.y+y*e.x;
        return(temp);
}
void complex::operator/(complex f)
{
       complex temp;                               //Numerator
       temp.x=x*f.x+y*(-f.y)*(-1);        //Real number of the numerator
       temp.y=x*(-f.y)+y*f.x;               //Imaginery number of the numerator
       float deno;                                  //Denominator
       deno=f.x*f.x-f.y*f.y*(-1);        //Similar to (a+b)(a-b)=a2-b2
       cout<<temp.x<<" + "<<temp.y<<"i / "<<deno;
}

void main()
{
      clrscr();
      complex c1(5,3),c2(3,2),c3=c1+c2,c4=c1-c2,c5=c1*c2;
      c1.display();
      c2.display();
      cout<<"Addition"<<endl;
      c3.display();
      cout<<"Subtraction"<<endl;
      c4.display();
      cout<<"Multiplication"<<endl;
      c5.display();
      cout<<"Division"<<endl;
      c1/c2;
     getch();
}

OUTPUT:
5 + 3i
3 + 2i
Addition
8 + 5i
Subtraction
2 + 1i
Multiplication
9 + 19i
Division
21 + -1i / 13

Monday, August 9, 2010

Program 11 : A simple program illustrating Constructor and Destructor

#include < iostream >
using namespace std;
// class declaration
class myclass 
{
               int a;
     public:
               myclass( ); //constructor
              ∼myclass( ); //destructor
              void show( );
};

myclass::myclass( ) 
{
     cout << "In constructor\n";
     a=10;
}
myclass::∼myclass( )
{
    cout << "Destructing...\n";
} // ...



void main( )
{
          myclass c;
}

OUTPUT

Note:
You will notice that initially you will only get the output

In Constructor

But,After exiting the output screen come back to program and refresh ( Alt+F5 ), Then you will the output 

Destructing...

The reason being that the constructor is called when the object is created and destructor is called when the object is destroyed.The object will be destroyed only when we have exited the main program. So we need to refresh after exiting the program and Tada!! You get the output "Destructing..."

Friday, August 6, 2010

Program 10 - Simple Interest (Asked in the test on 6/8/10)


This program takes in the prinicipal, rate and time as a screen input from the user.
The program is executed (run) 5 times using the 'FOR' loop.
It calculates the simple interest using the formula I = PTR/100.
The principal, rate, time and the simple interest are then outputted using the 'cout' command.

#include <iostream.h>
#include <conio.h>

void main()
{
     clrscr();
     int i;
     float  fsinterest,fprincipal,frate,ftime;
     for(i=4;i>=0;i--)
       {
          cout << "Enter the principal, rate & time : " << endl;
          cin>>fprincipal>>frate>>ftime;
          fsinterest=(fprincipal*frate*ftime)/100;
          cout << "Principal = $" << fprincipal << endl;
          cout << "Rate = " << frate << "%" << endl;
          cout << "Time = " << ftime << " years" << endl;
          cout << "Simple Interest = $" << fsinterest << endl;
        }
getch();
}

Program 9 - Employee Class advanced


The following program which utilizes the same class Employee with a few extensions:

class Employee
{
     int Empno;
     char *Ename;
     char *Add;
     float Salary, Comm, TotSal;

     public:
            void Input( );
            void Output( );
            void ChangeEmpno(int);                //function with argument of type int
            void ChangeEmpno2(int =2);         //function with default argument
            float Tot_sal( );                           //function with return type float
};

int main()
{
           Employee Emp1;
           Emp1.Input( );
           Emp1.Output( );

           cout<<Emp1.Tot_Sal( );
           
           Emp1.ChangeEmpno( );
           Emp1.ChangeEmpno(458);
           Emp1.ChangeEmpno2(100);

          return 0;
}

void Employee::Input()
{
          cin>>Empno>>Ename>>Add>>Salary>>Comm;
          TotSal=Tot_Sal( );               //Input() is calling Tot_Sal()
}
void Employee::Output( )
{
          cout<<Empno<<Ename<<Add<<Salary<<Comm<<TotSal;
}
void Employee::ChangeEmpno( )
{
          int NewEmpno;
          cin>>NewEmpno;

          Empno=NewEmpno;
}
void Employee::ChangeEmpno(int NewEmpno)
{
        Empno=NewEmpno;
}
void Employee::ChangeEmpno2(int IncEmpno)
{
        Empno+=IncEmpno;
}
float Employee::Tot_sal( )
{
        return Salary+Comm;
}

Program 8 - Employee Class program

This program takes the name,age, and salary of the employee as input and just displays the entered data.

#include<iostream.h>


class Employee
{
            private: 
                       char cname[30];
                       int iage,isalary;
            public:
                       void getdata( )                    //Function to get input from the user
                        {
                                 cout<<"Enter the Name of the Employee"<<endl;
                                 cin>>cname[30];
                                 cout<<"Enter the Age and salary of the employee"<<endl;
                                 cin>>iage>>isalary;
                            }


                       void display( )              //Function to display the entered data
                       {
                                 cout<<"***************************"<<endl; 
                                 cout<<"Name of the Employee : "<<name[30];
                                 cout<<"Age : "<<endl;
                                 cout<<"Salary : "<<endl;
                                 cout<<"***************************"<<endl;
                         }


};                                                                        //End of class


void main( )
{
             Employee e1,e2,e3;                 //Creating objects e1,e2,e3
               
             e1.getdata( );                           // Calling getdata function using object e1
             e2.getdata( );
             e3.getdata( );
          
             e1.display( );                          //Calling getdata function using object e1
             e2.display( );
              e3.display( );
}
    

Wednesday, August 4, 2010

Program 7 - Inline Functions

#include<iostream.h>


inline float mul(float x,float y)
{
               return(x*y);
}


inline double div(double p,double q)
{
              return(p/q);
}


int main( )
{
            float a = 12.345;
            float b =  9.82;
        
            cout<<mul(a,b)<<endl;
            cout<<div(a,b)<<endl;


           return 0;
}
    
Output:
121.228
1.25713    


Click here to read about Inline Functions







Program 6 -Operator Overloading illustrated by Matrix Addition,Subtraction and Multiplication Program

The following program implements Function Overloading by doing addition,subtraction and multiplication of Matrices.

#include<iostream.h>
#include<iomanio.h>


const int MAXROW=3,MAXCOL=3;
struct matrix
{
         int arr[MAXROW][MAXCOL];
};


matrix operator+(matrix a,matrix b);
matrix operator-(matrix a,matrix b);
matrix operator*(matrix a,matrix b);
void mat_print(matrix p);


void main( )
{
           matrix a = {
                                    1,2,3,
                                    4,5,6,
                                    7,8,9,
                              };
           matrix b = {
                                     1,2,3,
                                     4,5,6,
                                     7,8,9,
                               };


           matrix c,d,e,f;


          c=a+b;
          d=a*b;
          e=a+b*c;
          f=a-b*c+d;


          mat_print(c);
          mat_print(d);
          mat_print(e);
          mat_print(f);


}


matrix operator+(matrix a,matrix b)
{
          matrix c;
          int i,j;


          for(i=0;i<MAXROW;i++)
          {
                        for(j=0;j<MAXROW;j++)
                                c.arr[i][j] = a.arr[i][j] + b.arr[i][j];
            }
         return c;
}



matrix operator-(matrix a,matrix b)



{
          matrix c;
          int i,j;

          for(i=0;i<MAXROW;i++)
          {
                        for(j=0;j<MAXROW;j++)
                                c.arr[i][j] = a.arr[i][j] - b.arr[i][j];
            }
         return c;
}



matrix operator*(matrix a,matrix b)



{
          matrix c;
          int i,j,k;

          for(i=0;i<MAXROW;i++)
          {
                        for(j=0;j<MAXROW;j++)
                          {
                                     c.arr[i][j]=0;
                                     for(k=0;k<MAXCOL;k++)      
                                                    c.arr[i][j] + = a.arr[i][k] * b.arr[k][j];
                            }
            }
          return c;
}

void mat_print(matrix p)
{
            int i,j;

            cout<<endl<<endl;
            for(i=0;i<MAXROW;i++)
             {
                          cout<<endl;
                          for(j=0;j<MAXCOL;j++)
                                    cout<<setw(5)<<p.arr[i][j];
               }
}

Program 5- Program to demonstrate Function Overloading.

The program returns the absolute value of an argument.

#include<iostream.h>
void main( )
{
        int i=-25,j;
        long l=-100000L,m;
        double d=-12.34,e;
        int abs(int);
        long abs(long);
        double abs(double);


        j=abs(i);
        m=abs(l);
        e=abs(d);


        cout<<endl<<j<<endl<<m<<e;
}


int abs(int ii)
{
         return(ii>0?ii:ii*-1);
}
long abs(long ll)
{
         return(ll>0?ll:ll*-1);
}
double abs(double dd)
{
         return(dd>0?dd:dd*-1);
}


Click here to read about Function Overloading


      

Tuesday, August 3, 2010

Program 4- Program to switch between different cases.


This program takes in the user's choice as a screen input.
Depending on the user's choice, it switches between the different cases.
The appropriate message is then outputted using the 'cout' command.

#include <iostream.h>
#include <conio.h>

int main( )
{
        clrscr( );
        int choice;
        cout << "1. Talk" << endl;
        cout << "2. Eat" << endl;
        cout << "3. Play" << endl;
        cout << "4. Sleep" << endl;
        cout << "Enter your choice : " << endl;
        cin>>choice;

       switch(choice)
       {
            case 1 : 
            cout << "You chose to talk...talking too much is a bad habit." << endl;
            break;
           case 2 : 
           cout << "You chose to eat...eating healthy foodstuff is good." << endl;
           break;
           case 3 : 
           cout << "You chose to play...playing too much everyday is bad." << endl;
           break;
          case 4 : 
          cout << "You chose to sleep...sleeping enough is a good habit." << endl;
          break;
         default : 
         cout << "You did not choose anything...so exit this program." << endl;
       }
getch();
}

Sample Input:
3

Sample Output:



You chose to play...playing too much everyday is bad.

Program 3- Program to find if the number is prime or composite.


This program takes in an integer num1 as a screen input from the user.
It then determines whether the integer is prime or composite.
It finally outputs the approriate message by writing to the 'cout' stream.

#include <iostream.h>
#include <conio.h>
#include <process.h>

void main()
{
            clrscr();
            int num1,x;
            cout << "Enter an integer : " << endl;
            cin>>num1;
            for(x=2;x<num1;x++)
                 {
                      if(num1%x==0)
                          {
                             cout << num1 << " is a composite number." << endl;
                           }
                      else
                          {
                             cout << num1 << " is a prime number." << endl;                                            
                           }
                      }

 getch();
 exit(0);
}

Sample Input:
21

Sample Output:
21 is a composite number.

Program 2 - Program to enter the sale value and print the agent's commission


This program takes in the total sale value as a screen input from the user.
The program then calculates the agent's commission with the help of the 'IF-ELSE' command as follows :
5% if the total sale value is less than or equal to Rs10000.
10% if the total sale value is less than or equal to Rs.25000.
20% if the total sale value is greater than Rs.25000. It then outputs the agent's commission using the 'cout' command.


#include <iostream.h>
#include <conio.h>

void main( )
{
           clrscr( );
           long int svalue;
           float commission;
           cout << "Enter the total sale value : " << endl;
           cin>>svalue;
         if(svalue<=10000)
         {
                     commission=svalue*5/100;
                     cout << "For a total sale value of $" << svalue << ", ";
                     cout << "the agent's commission is $" << commission;
          }
         else if(svalue<=25000)
          {
                   commission=svalue*10/100;
                   cout << "For a total sale value of $" << svalue << ", ";
                   cout << "the agent's commission is $" << commission;
            }
        else if(svalue>25000)
          {
                   commission=svalue*20/100;
                   cout << "For a total sale value of $" << svalue << ", ";
                   cout << "the agent's commission is $" << commission;
            }
getch();
}                  



Sample Input:
26000

Sample Output:
For a total sale value of Rs.26000,
the agent's commission is Rs.5200

Program 1: a Simple program depicting the use of Class

#include<iostream.h>


class rectangle
{
        private:
                    int len,br;
        public:
                    void getdata( )
                    {
                           cout<<<"Enter length and breadth";
                           cin>>len>>br;
                      }


                 void setdata(int l,int b)
                  {
                           len=l;
                           br=b;
                   }


              void displaydata()
                {
                           cout<<<"Length = "<
                           cout<<<"Breadth = "<
                  }


              void area_peri()
                 {
                           int a,p;
                           a=len*br;
                           p=2*(len+br);
                           cout<<<"Area = "<
                           cout<<<"Perimeter ="<
                   }
};                                                       //End of Class


void main( )
{
              rectangle r1,r2,r3;        //define three objects of class rectangle
    
              r1.setdata(10,20);       //set data in elements of the object
              r1.display( );                //display the data set by setdata()
              r1.area_peri( );            //calculate and print area and perimeter


              r2.setdata(5,8);
              r2.displaydata( );
              r2.area_peri( );


             r3.getdata( );             //receive data from keyboard
            r3.displaydata( );
            r3.area_peri( );
}