Thursday, December 27, 2012

Array Object – C++



The Array object is meant to store multiple values in a single variable. Object arrays are more flexible way to solve a problem. It store values of different types in a single collection. An object array also can store a and reference. Using of array of object also reduce the runtime performance.


Example – Input numbers using Array of Objects and print the sum


#include <iostream.h>

  class ObjArr
      {
           private:
              int num;
           public:
              void input()
                   {
                        cin>>num;
                   }
              int disp(int s)
                   {
                        cout<<num<<" ";
                        s=s+num;
                        return s;
                   }

      };

  void main()
      {
           clrscr();
           ObjArr OB[10];
           int i,sum=0;
           cout<<"\n\tEnter 10 No. \n";
           for(i=0;i<10;i++)
              {
                   cout<<"\t";
                   OB[i].input();
              }
           cout<<"\n\tValues. ";
           for(i=0;i<10;i++)
              {
                   sum=OB[i].disp(sum);
              }
           cout<<"\n\tSum = "<<sum;
      }


Example – Input ‘N’ numbers using Array of Objects and Sorting the elements using Bubble Sort Technique.


#include <iostream.h>

  class ObjArrSrt
      {
           private:
              int num;
           public:
              void Getdata();
              void Disp();
              void Bsort(ObjArrSrt *, int);
       };
  void ObjArrSrt::Getdata()
      {
           cout<<"\t";
           cin>>num;
      }
  void ObjArrSrt::Bsort(ObjArrSrt *Bub,int n)
      {
           int temp;
           for(int i=0;i<n;i++)
              {
                   for(int j=0;j<n-i-1;j++)
                        {
                            if(Bub[j].num>Bub[j+1].num)
                                {
                                      temp=Bub[j].num;
                                      Bub[j].num=Bub[j+1].num;
                                      Bub[j+1].num=temp;
                                }
                        }
              }
      }
  void ObjArrSrt::Disp()
      {
           cout<<num<<" ";
      }

  void main()
      {
           int n;
           ObjArrSrt *Ob,Obj;
           cout<<"\n\tEnter the Size : ";
           cin>>n;
           Ob=new ObjArrSrt[n];
           cout<<"\n\tEnter "<<n<<" Elements : ";
           for(int i=0;i<n;i++)
              {
                   Ob[i].Getdata();
              }
           Obj.Bsort(Ob,n);
           cout<<"\n\tOriginal Elements : ";
           for(i=0;i<n;i++)
              {
                   Ob[i].Disp();
              }
           cout<<"\n\tElements After Sorting : ";
           for(i=0;i<n;i++)
              {
                   Ob[i].Disp();
              }
           getch();
      }


No comments: