Pages

Monday 20 September 2021

Program to illustrate Arrays of Objects in c++

An array of a class type is also known as an array of objects. An array of objects is declared in the same way as an array of any built-in data type.

//Program to illustrate one dimensional static array
#include<iostream.h>
#include<conio.h>
class student
 {
  int Id;
  char Name[25];
  public:
  void GetData()           //Statement 1 : Defining GetData()
  {
   cout<<"\nEnter student Id : ";
   cin>>Id;
   cout<<"\nEnter student Name : ";
   cin>>Name;
  }
  void PutData()           //Statement 2 : Defining PutData()
  {
   cout<<Id<<"\t\t"<<Name;
  }
};
void main()
{
  int i;
  clrscr();
  student s[3];
  for(i=0;i<3;i++)
  {
   cout<<"\nEnter details of "<<i+1<<" students";
   s[i].GetData();
  }
  cout<<"Student Details"<<endl;
  cout<<"Student Id"<<"\t"<<"Student Name"<<endl;
  for(i=0;i<3;i++)
  {
  s[i].PutData();
  cout<<endl;
  }
getch();
}

//Program to illustrate one dimensional dynamic array
#include<iostream.h>
#include<conio.h>
class std
 {
  int id;
  char name[25];
  public:
  void getdata();           //Statement 1 : Defining GetData()
  void putdata();
 };
void std::getdata()
  {
   cout<<"\nEnter student Id : ";
   cin>>id;
   cout<<"\nEnter student Name : ";
   cin>>name;
  }
void std::putdata()           //Statement 2 : Defining PutData()
  {
   cout<<id<<"\t\t"<<name;
  }

void main()
{
  int i,n;
  std s[160];
  clrscr();
  cout<<"Enter the size of the Array";
  cin>>n;
  for(i=0;i<n;i++)
  {
   cout<<"\nEnter details of "<<i+1<<" students";
   s[i].getdata();
  }
  cout<<"Student Details"<<endl;
  cout<<"Student Id"<<"\t"<<"Student Name"<<endl;
  for(i=0;i<n;i++)
  {
  s[i].putdata();
  cout<<endl;
  }
getch();
}

No comments:

Post a Comment

Constructors & Destructors in c++

  Constructors :  A Constructor is a special member function, which is used to initialize the objects of its class. The Constructor is invok...