Return to the C++ Demos Home Page

SAMS Teach Yourself C++ in 21 Days

Chapter Twelve

Prog 1 :  Simple Arrays

// STYC++in21 Chapter 12
//
//   Arrays and Linked lists
//
//  

#include <iostream.h>

class Cat
{
   public :
   Cat() { itsAge = 1; itsWeight=5; }
   ~Cat(){}

   int getAge() const { return itsAge; }
   int getWeight() const { return itsWeight; }
   void setAge(int age) { itsAge = age; }

   private:
   int itsAge;
   int itsWeight;

};

// driver

int main()
{

   Cat litter[5];
   int i;

    for (i=0; i<5; i++ )
	   litter[i].setAge(2*i+1);


	for (i=0; i<5; i++ )
	   cout << "Cat #" << i+1 << " is " << litter[i].getAge() << " old\n";

   return 0;

} // end of source

Prog 2 :  Multidimensional Arrays

// STYC++ in 21 chap 12 prog 2
//
//   Multidimensional arrays
//
//

#include <iostream.h>

int main()
{

   int someArray [5][2] = { {0,0}, {1,2}, {3,4}, {5,6}, {7,8} };

   for (int i=0; i<5; i++)
     for (int j=0; j<2; j++)
	   cout << "someArray [" << i << "][" << j << "] : " << someArray[i][j] << '\n';


return 0;

} // end of source

Prog 3 : An Array of Pointers to data on the heap

// STYC++in21 Chapter 12 prog 3
//
//   An array of pointers on the heap
//
//  

#include <iostream.h>

class Cat
{
   public :
   Cat() { itsAge = 1; itsWeight=5; }
   ~Cat(){}

   int getAge() const { return itsAge; }
   int getWeight() const { return itsWeight; }
   void setAge(int age) { itsAge = age; }

   private:
   int itsAge;
   int itsWeight;

};

// driver

int main()
{

   Cat *family[500];
   int i;
   Cat *p2cat;

      for (i=0; i<500; i++)
	  {
		  p2cat = new Cat;
		  p2cat->setAge(2*i+1);
		  family[i] = p2cat;
	  }

	  for (i=0; i<500; i++)
	  	  cout << "Cat #" << i+1 << " : " << family[i]->getAge() << '\n';

   return 0;

} // end of source

Prog 4 : An array kept entirely on the heap

// STYC++in21 Chapter 12 prog 3
//
//  Entire Array on the heap
//
//  

#include <iostream.h>

class Cat
{
   public :
   Cat() { itsAge = 1; itsWeight=5; }
   ~Cat();

   int getAge() const { return itsAge; }
   int getWeight() const { return itsWeight; }
   void setAge(int age) { itsAge = age; }

   private:
   int itsAge;
   int itsWeight;

};

// destructor
Cat::~Cat()
{
	//  cout << "Cat Destructor Called!\n";  // only to test delete
}


// driver

int main()
{

   Cat *family = new Cat[500];
   int i;
   

      for (i=0; i<500; i++)
	  {
		  family[i].setAge(2*i+1);
	  }

	  for (i=0; i<500; i++)
	  	  cout << "Cat #" << i+1 << " : " << family[i].getAge() << '\n';

	  delete [] family;


   return 0;

} // end of source

Prog 5 : Simple ex of cin.get() - Char arrays

// chapter 12 prog 5 STYC++ in 21
//
//  Dealing with Strings a bit...
//
//
//

#include <iostream.h>

int main()
{

  char buffer[80];
  cout << "Enter the String: ";
  cin.get(buffer, 79);
  cout << "here's the buffer : " << buffer << endl;
  return 0;

} //eos

Return to the C++ Demos Home Page