Rabu, 01 April 2026

C++ From Year 1995 File From "N"

 // File name: NAMENAME.CPP

// Demonstration of implicit use of constructors

// by Visual C++


#include <iostream.h>

#include <string.h>


//

// Name - a trivial class

//

class Name

  {

    public:

      // Constructors

      Name();                     // Default

      Name(const Name& n);        // Copy

      Name(const char * newName); // Normal            

      // Destructor

      ~Name();

      // Access function

      const char * GetName() const;

    private:            

      // Data member

      char * name;

  };


// Default constructor - ensure name is initialized

Name::Name()

  {

    name = 0;

    cout << "Default constructor used" << endl;

  }


// Copy constructor - ensure string is duplicated  

Name::Name(const Name& n)

  {

    if (n.name)

      {

         name = new char[strlen(n.name) + 1];

         strcpy(name,n.name);

      }

    else

      name = 0;

    cout << "Copy constructor used - "

         << (name == 0?name : "") << endl;

  }

  

// Make a name for myself

Name::Name(const char * newName)

  {

    if (newName)

      {

         name = new char[strlen(newName) + 1];

         strcpy(name,newName);

      }

    else

      name = 0;

    cout << "const char* constructor used - "

         << (name != 0?name : "") << endl;

  }          


// Destructor

Name::~Name()

  {

    cout << "Destructor - " << (name != 0?name : "") << endl;

    delete name;

  }


// Provide access

const char * Name::GetName() const

  {

    return name;

  }


// Global function with pass by value

void PrintName(Name n)

  {

    cout << "In PrintName  - " << n.GetName() << endl;

  }  


// main() function to excercise the class

void main()

  {

    cout << "-- Start of main() --" << endl;

    Name n("Norman Lamont");

    

    cout << "-- Before PrintName --" << endl;

    PrintName(n);

    

    cout << "-- Before n1 declaration --" << endl;

    Name n1(n);

    

    cout << "-- Before n2 declaration --" << endl;

    Name n2;


    cout << "-- Before n2 = n1 --" << endl;

    n2 = n1; // Unsafe!!!


    cout << "-- End of main() --" << endl;

  }


      ====================================

// Filename: INITIALS.CPP

// Shows a routine that when given a name finds

// the initials

//


#include <string.h>  // header for strlen function

#include <iostream.h>


// GetInitials prototype: returns 1 if successful,

//                                0 if fails

int GetInitials(char initials[],const char name[]);


void main()

  {

     char initials[15] = ""; // Allow for silly strings 

     char name[30] = "";

     while (1)               // Do forever

       {

          cout << "Type name, (0 to quit): ";

          cin.getline(name,30); 

          if (name[0] == '0')// Stop when the user asks

            break;

              

          //

          // Extract the initials, and report if error

          //

          if (GetInitials(initials,name))

            {

               cout << "The initials for '" << name 

                    << "' are: '" << initials << "'" << endl;

            }

          else

            {

               cout << "Something wrong with '" 

               << name << "'" << endl;

            }  

       }

  }

//***********************************************************  

int GetInitials(char initials[],const char name[])

  {

    int count = 0;        

    int initialCount = 0;

    

    int length = strlen(name);

    if (length == 0) // error if no string

      return 0;                               

     

    while (count < length)

      {

        while (count < length

               && name[count] == ' ')

          count++;

        if (count < length)

          {

            initials[initialCount] = name[count];

            initialCount++;

            count++;

          }

        while (count < length

               && name[count] != ' ')

          count++;

      }

    initials[initialCount] = '\0';// Ensure terminated string

    return (initialCount > 0);    // Success if found

                                  // one or more initials

  } 

=================================

// Filename: NESTFOR.CPP

// Two nested loops

#include <iostream.h>

void main()

{

  int inner, outer;


  // One loop nested in another

  cout << "Showing the loop control variables:" << endl;

  cout << "Outer   Inner" << endl;

  for (outer = 0; outer < 2; outer++)

    { 

      for (inner = 0; inner <= 3; inner++)

        { 

          // The '\t' outputs a tab character

          cout << outer << '\t' << inner << endl; 

        }

    }


  cout << endl;   // Blank line between loop outputs


  cout << "Here is a loop from 1 to 10, printed three times:" << endl;

  for (outer = 0; outer < 3; outer++)

    { 

      for (inner = 1; inner <= 10; inner++)

        { 

          cout << inner << ' '; 

        }

      cout << endl;   // Executes once each outer iteration

    }


  return;

}

==============================

// Filename: NEWLINE.CPP

// Program that uses endl

#include <iostream.h>


void main()

{

  cout << "Line #1";

  cout << "Line #2";


  cout << endl << endl;

  cout << "Line #3" << endl;

  cout << "Line #4";

  return;

}

=========================

#include <iostream.h>

void main()

{

  int out, in;

  for (out = 0; out < 10; out++)

   {  

     for (in = 0; in < 5; in++)

      {

        if ((in * out) % 2)

          {  

            cout << in << '\t' << out << endl;

            break;

          }

        cout << '\x07';

      }

    }

}

=============================
// Filename: NOBREAKS.CPP
// Not using break statements inside a switch lets
// you cascade through the subsequent case blocks
#include <iostream.h>

void main()
{
  char request;

  cout << "Sales Reporting System"  << endl << endl;

  cout << "Do you want the Country, Region, State, or Local report";
  cout << " (C, R, S, or L)? ";
  cin >> request;
  cout << endl;

  //
  // Convert to uppercase - letters are contiguous
  //
  if (request >= 'a' || request <= 'z')
    request += ('A' - 'a');
  
  switch (request)
    { 
      case ('C') : 
        { 
          cout << "Country's sales: $343,454.32" << endl; 
        }
      case ('R') : 
        { 
          cout << "Region's sales: $64,682.01" << endl; 
        }
      case ('S') : 
        { 
          cout << "State's sales: $12,309.82" << endl; 
        }
      case ('L') : 
        { 
          cout << "Local's sales: $3,654.58" << endl;
          break; 
        }
      default    : 
        { 
          cout << "You did not enter C, R, S, or L"  << endl;
          break; 
        }
    }
  return;
}
==============================
// Filename: NUMSORT.CPP
// Initializes and sorts an array of 20 values.
// First, an ascending sort is done. Then the
// program takes those sorted values and
// performs a descending sort.
const int NUM = 20;

#include <iostream.h>

// Program prototypes follow
void prAra(int ara[NUM]);
void ascSort(int ara[NUM]);
void desSort(int ara[NUM]);
void main()
{
  int ara[NUM] = {53, 23, 12, 56, 88,  7, 32, 41, 59, 91,
                  88, 62,  4, 74, 32, 33, 42, 26, 80,  3};
  cout << "Before the sort, here are the values: " << endl;
  prAra(ara);

  // Perform an ascending sort
  ascSort(ara);
  cout << endl << endl << "After the ascending sort:" << endl;
  prAra(ara);

  // Perform a descending sort
  desSort(ara);
  cout << endl << endl << "After the descending sort:" << endl;
  prAra(ara);

  return;
}
//**********************************************************
void prAra(int ara[NUM])
{
  int ctr;   // for-loop control variable
  for (ctr = 0; ctr < NUM; ctr++)
    { if ((ctr % 10) == 0)   // Print a newline after
        { cout << endl; }    // every 10 values
      cout.width(4);
      cout << ara[ctr]; // Print values in four spaces
    }
  return;
}
//**********************************************************
void ascSort(int ara[NUM])
{
  int inner, outer;   // for-loop control variables
  int temp;           // Temporary value for swapping
  int didSwap;        // 1 if a swap took place in each pass
  for (outer = 0; outer < (NUM - 1); outer++)
    {
      didSwap = 0;   // Initialize after each pass
      // Next loop steps through each pair of values
      for (inner = outer; inner < NUM; inner++)
        {
          if (ara[outer] > ara[inner])   // First of two is higher
            { temp = ara[outer];   // Swap
              ara[outer] = ara[inner];
              ara[inner] = temp;
              didSwap = 1;   // Indicate that a swap occurred
            }
        }
      if (!didSwap)   // If no swap happened,
        { break; }    // terminate the sort
    }
  return;
}
//**********************************************************
void desSort(int ara[NUM])
{
  // Only one change is needed for a descending sort
  int inner, outer;   // for-loop control variables
  int temp;           // Temporary value for swapping
  int didSwap;        // 1 if a swap took place in each pass
  for (outer = 0; outer < (NUM - 1); outer++)
    {
      didSwap = 0;   // Initialize after each pass
      // Next loop steps through each pair of values
      for (inner = outer; inner < NUM; inner++)
        {
          if (ara[outer] < ara[inner])   // First of two is higher
            { temp = ara[outer];   // Swap
              ara[outer] = ara[inner];
              ara[inner] = temp;
              didSwap = 1;   // Indicate that a swap occurred
            }
        }
      if (!didSwap)   // If no swap happened,
        { break; }    // terminate the sort
    }
  return;
}
================================
// Filename: NUMSORT2.CPP
// Initializes and sorts an array of 20 values.
// First, an asending sort is done, and then
// the program takes those sorted values and
// performs a descending sort.

const int NUM = 20;

#include <iostream.h>

// Program prototypes follow
void prAra(int ara[NUM]);
void Sort(int direction, int ara[NUM]);
int Test(int direction, int val1, int val2);

void main()
{
  int ara[NUM] = {53, 23, 12, 56, 88,  7, 32, 41, 59, 91,
                  88, 62,  4, 74, 32, 33, 42, 26, 80,  3};
  cout << "Before the sort, here are the values: " << endl;
  prAra(ara);

  // Perform an asending sort
  Sort(1, ara);  // 1 means ascending
  cout << endl << endl << "After the ascending sort:" << endl;
  prAra(ara);

  // Perform a descending sort
  Sort(0, ara);  // 0 means descending
  cout << endl << endl << "After the descending sort:" << endl;
  prAra(ara);
  return;
}
//**********************************************************
void prAra(int ara[NUM])
{
  int ctr;   // for-loop control variable
  for (ctr=0; ctr<NUM; ctr++)
    { if ((ctr % 10) == 0)  // Print a newline after
        { cout << endl; }   // every ten values
      cout.width(4);
      cout << ara[ctr];  // Prints values in 4 spaces
    }
  return;
}
//**********************************************************
void Sort(int direction, int ara[NUM])
{
  int inner, outer;    // for-loop control variables
  int temp;            // Temporary value for swapping
  int didSwap;         // 1 if a swap took place in each pass
  for (outer = 0; outer < (NUM-1); outer++)
    {
      didSwap = 0;   // Initialize after each pass
      // Next loop steps through each pair of values
      for (inner = outer; inner < NUM; inner++)
        {
          if (Test(direction, ara[outer], ara[inner]))
            { temp = ara[outer];   // Swap
              ara[outer] = ara[inner];
              ara[inner] = temp;
              didSwap = 1;  // Indicate that a swap occurred
            }
        }
      if (!didSwap)  // If no swap happened...
        { break; }   // Terminate the sort
    }
  return;
}
//**********************************************************
int Test(int direction, int val1, int val2)
{
  int trueFalse;  // Holds result of swap
  // direction is 1 for asending sort and 0 for descending
  if (direction)  // Asending
    { trueFalse = (val1 > val2); }
  else            // Descending
    { trueFalse = (val1 < val2); }
  return trueFalse;
}
===============================
// Filename: NUMSWITC.CPP
// Print the name of the number entered by the user
#include <iostream.h>
void main()
{
  int num;

  do
  { cout << "Enter a number from 1 to 5: ";
    cin >> num;
  } while ((num < 1) || (num > 5));

  cout << "You entered a ";  // The switch will finish this

  switch (num)
  { case (1) : { cout << "one." << endl;
                 break; }
    case (2) : { cout << "two." << endl;
                 break; }
    case (3) : { cout << "three." << endl;
                 break; }
    case (4) : { cout << "four." << endl;
                 break; }
    case (5) : { cout << "five." << endl;
                 break; }
  }
  return;
}

C++ From Year 1995 File From "M"

 // Filename: MATHMENU.CPP

// Uses a switch statement to perform

// menu actions for the user

#include <iostream.h>


void main()

{

  const int PI = 3.14159;

  int menu;       // Will hold menu result

  int num;        // Will hold user's numeric value

  float result;   // Will hold computed answer


  cout << "Math Calculations" << endl << endl;

  cout << "Please enter a number from 1 to 30: ";

  cin >> num;

  if ( (num < 1) && (num > 30));   

    {

      return;  // Exit if bad input

    }

    

  cout << "Here are your choices:" << endl << endl;

  cout << "\t1. Calculate the absolute value" << endl;

  cout << "\t2. Calculate the square" << endl;

  cout << "\t3. Calculate the cube" << endl;

  cout << "\t4. Calculate a circle's area" << endl;

  cout << "\t   using your radius" << endl;

  cout << endl << "What do you want to do? ";

  cin >> menu;


  switch (menu)

    { 

      case (1) : 

        { 

          result = ((num < 0)? -num : num);

          break;

        }

      case (2) : 

        { 

          result = num * num;

          break;

        }

      case (3) : 

        { 

          result = num * num * num;

          break;

        }

      case (4) : 

        { 

          result = PI * (num * num);

          break;

        }

      default  : 

        { 

          cout << "You did not enter 1, 2, 3, or 4" << endl;

          return;   // Terminate the whole program

                    // No need for a break

        }

    }


  cout << endl << "Here is your computed value: " 

       << result << endl;

  return;

}

==================================




// File Name : MFC.CPP

// A very simple Windows program

//

// To compile and run this, you will need to 

// use the MFC.MAK project included with the

// source. Choose Project | Open | MFC.MAK

//

#include<afxwin.h> // This lives in a different include 

                   // directory


//------------------------------------------------------------

// SimpleApp is a class that hides the Windows equivalent

// of main()

//

class SimpleApp:public CWinApp

 {

   public:

   BOOL InitInstance() // A virtual function - trust me!

      {

        CString title("Hello World");  // A string class

        title += "!"; // Classes can define operators too.

                      // Define the addition to concatenate

                      // a string.

        // Make a window object with a frame border

        CFrameWnd* mainWindow = new CFrameWnd;

        // Tell Windows to make a window

        mainWindow->Create(0,title);    

        // Assign the window to the application

        m_pMainWnd = mainWindow;               

        // Tell Windows to show the window

        m_pMainWnd->ShowWindow(m_nCmdShow);

        // Tell Windows to make sure that the window

        // is properly drawn.

        m_pMainWnd->UpdateWindow();

        // Tell the base application that we successfully

        // made a window

        return TRUE;

      }


  };



SimpleApp SimpleApp;  // This makes a global object

                      // which includes a main()

                      // that Windows can find

=========================================

             # Microsoft Visual C++ generated build script - Do not modify


PROJ = MFC

DEBUG = 0

PROGTYPE = 0

CALLER = 

ARGS = 

DLLS = 

D_RCDEFINES = -d_DEBUG

R_RCDEFINES = -dNDEBUG

ORIGIN = MSVC

ORIGIN_VER = 1.00

PROJPATH = C:\WORD6\VC12\SOURCE\

USEMFC = 1

CC = cl

CPP = cl

CXX = cl

CCREATEPCHFLAG = 

CPPCREATEPCHFLAG = 

CUSEPCHFLAG = 

CPPUSEPCHFLAG = 

FIRSTC =             

FIRSTCPP = MFC.CPP     

RC = rc

CFLAGS_D_WEXE = /nologo /G2 /W3 /Zi /AM /Od /D "_DEBUG" /FR /GA /Fd"MFC.PDB"

CFLAGS_R_WEXE = /nologo /G2 /W3 /AM /O1 /D "NDEBUG" /FR /GA 

LFLAGS_D_WEXE = /NOLOGO /ONERROR:NOEXE /NOD /PACKC:61440 /CO /ALIGN:16 /STACK:10240

LFLAGS_R_WEXE = /NOLOGO /ONERROR:NOEXE /NOD /PACKC:61440 /ALIGN:16 /STACK:10240

LIBS_D_WEXE = mafxcwd oldnames libw commdlg shell olecli olesvr mlibcew

LIBS_R_WEXE = mafxcw oldnames libw commdlg shell olecli olesvr mlibcew

RCFLAGS = /nologo

RESFLAGS = /nologo

RUNFLAGS = 

DEFFILE = MFC.DEF

OBJS_EXT = 

LIBS_EXT = 

!if "$(DEBUG)" == "1"

CFLAGS = $(CFLAGS_D_WEXE)

LFLAGS = $(LFLAGS_D_WEXE)

LIBS = $(LIBS_D_WEXE)

MAPFILE = nul

RCDEFINES = $(D_RCDEFINES)

!else

CFLAGS = $(CFLAGS_R_WEXE)

LFLAGS = $(LFLAGS_R_WEXE)

LIBS = $(LIBS_R_WEXE)

MAPFILE = nul

RCDEFINES = $(R_RCDEFINES)

!endif

!if [if exist MSVC.BND del MSVC.BND]

!endif

SBRS = MFC.SBR



all: $(PROJ).EXE $(PROJ).BSC


MFC.OBJ: MFC.CPP $(MFC_DEP)

$(CPP) $(CFLAGS) $(CPPCREATEPCHFLAG) /c MFC.CPP



$(PROJ).EXE:: MFC.OBJ $(OBJS_EXT) $(DEFFILE)

echo >NUL @<<$(PROJ).CRF

MFC.OBJ +

$(OBJS_EXT)

$(PROJ).EXE

$(MAPFILE)

c:\msvc\lib\+

c:\msvc\mfc\lib\+

$(LIBS)

$(DEFFILE);

<<

link $(LFLAGS) @$(PROJ).CRF

$(RC) $(RESFLAGS) $@



run: $(PROJ).EXE

$(PROJ) $(RUNFLAGS)



$(PROJ).BSC: $(SBRS)

bscmake @<<

/o$@ $(SBRS)

<<

====================================
NAME      MFC
EXETYPE   WINDOWS
CODE      PRELOAD MOVEABLE DISCARDABLE
DATA      PRELOAD MOVEABLE MULTIPLE
HEAPSIZE  1024
=============================
// Filename: MINMAX.CPP
// Finds the minimum and maximum values in an array

const int NUM = 20;

#include <iostream.h>

void prAra(int ara[NUM]);
int min(int ara[NUM]);
int max(int ara[NUM]);

void main()
{
  int ara[NUM] = {53, 23, 12, 56, 88,  7, 32, 41, 59, 91,
                  88, 62,  4, 74, 32, 33, 42, 26, 80,  3};
  cout << "Here is the array:" << endl;
  prAra(ara);
  cout << endl << endl << endl;
  cout << "The lowest value is " << min(ara) << endl << endl;
  cout << "The highest value is " << max(ara) << endl;

  return;
}
//**********************************************************
void prAra(int ara[NUM])
{
  int ctr;   // for-loop control variable
  for (ctr = 0; ctr < NUM; ctr++)
    { if ((ctr % 10) == 0)   // Print a newline after
        { cout << endl; }    // every 10 values
      cout.width(4);   // Print values in 4 spaces
      cout << ara[ctr];   // Print values in 4 spaces
    }
  return;
}
//**********************************************************
int min(int ara[NUM])
{
  int lowInt = 32767;
  int ctr;
  for (ctr = 0; ctr < NUM; ctr++)
    { if (ara[ctr] < lowInt)
        { lowInt = ara[ctr]; }
    }
  return lowInt;
}
//**********************************************************
int max(int ara[NUM])
{
  int highInt = -32768;
  int ctr;
  for (ctr = 0; ctr < NUM; ctr++)
    { if (ara[ctr] > highInt)
        { highInt = ara[ctr]; }
    }
  return highInt;
}
===========================
// Filename: MOREDIV.CPP
 // Computes two kinds of divisions and the modulus
 #include <iostream.h>
 void main()
 {
   int people, events, avgEv;
   int leftOver;        // Will hold modulus
   float floatPeople;   // Needed to force regular division
   float exact;         // Will hold exact average

   cout << "How many people will attend? ";
   cin >> people;
   cout << "How many events are scheduled? ";
   cin >> events;

   // Compute the integer average number of people per event
   avgEv = people / events;   // The integer division ensures
                              // that the fractional part of
                              // the answer is discarded
   cout << endl << "There will be an average of " << avgEv
        << " people per event." << endl;
   leftOver = people % events;
   cout << "There will be " << leftOver
        << " without an event at any one time." << endl;
   floatPeople = people;  // Converts the integer to a floating-point
   exact = floatPeople / events;
   cout << "The exact average number of people per event is "
        << exact;
   return;
 }
=============================
// Filename: MOVIES.CPP
// Stores and prints old movie titles
#include <iostream.h>

void main()
{
  int c;
  char * movies[] = {"To Italy Again!",
                     "Love Might Survive",
                     "My Computer and Me",
                     "Blabby",
                     "The First Man On Neptune"};
  cout << "Here are my all-time favorites:" << endl;
  for (c = 0; c < 5; c++)
    { cout << movies[c] << endl; }

  return;
}
===========================

C++ From Year 1995 File From "L"

 // Filename: LEMONS.CPP

 // Child's lemonade sale-tracking program

 

 #include <iostream.h>


 // Lemonade class declaration comes next

 class Lemon {

 private:

   int totalLeft;             // Will start at 100

   int sugarTeasp;            // Starts at 80

   double total;              // Income for day

 public:

   void init(void);           // Initialize members upon startup

   void showTot(void);        // Print the day's total income

   void buySweet(void);       // When customer buys sweetened

   void buyUnSweet(void);     // When customer buys unsweetened

 };

 // The member functions appear next. The scope resolution

 // operator, ::, tells Visual C++ that these are member

 // functions of the Lemon class and not regular non-class

 // functions such as those that might follow main()

 void Lemon::init(void)

 {  totalLeft = 100;

    sugarTeasp = 80;

    total = 0.0;

 }

 void Lemon::showTot(void)

 { cout.precision(2);

   cout.setf(ios::fixed);

   cout.setf(ios::showpoint);

   cout << endl << "Total so far today is $" << total << endl << endl;

 }

 void Lemon::buySweet(void)

 {

   if (totalLeft == 0)

     { cerr << "Sorry, no more lemonade is left." << endl << endl;}

   else

     if (sugarTeasp == 0)

       { cerr << "No more sugar is left. Sorry." << endl << endl; }

     else

       { cout << "Enjoy your drink!" << endl << endl;

         totalLeft--;         // One less glass left

         sugarTeasp -= 2;     // Each glass takes 2 teaspoons

         total += .50;

       }

 }

 void Lemon:: buyUnSweet(void)

 {

   if (totalLeft == 0)

     { cerr << "Sorry, no more lemonade is left." << endl << endl;}

   else

     { cout << "Enjoy your drink!"<< endl << endl;

       totalLeft--;           // One less glass left

       total += .45;

     }

 }

 ////////////////// Class ends here /////////////////////////

 main()

 {

   Lemon drink;   // Define a class variable

   int ans;

   drink.init();  // Initialize data members to start of day

   do {

     cout << "What's happening?" << endl;

     cout << "  1. Sell a sweetened." << endl;

     cout << "  2. Sell an unsweetened." << endl;

     cout << "  3. Show total sales so far." << endl;

     cout << "  4. Quit the program." << endl;

     cout << "What do you want to do? ";

     cin >> ans;

     switch (ans)

      { case 1 : drink.buySweet();     // Update proper totals

  break;

        case 2 : drink.buyUnSweet();

  break;

        case 3 : drink.showTot();

  break;

        case 4 : drink.showTot();      // Print total one last time

  return 1;

      }

     } while (ans >=1 && ans <= 4);

   return 0;

 }

============================

// Filename: LOGICALS.CPP

 // A program with an if, an if-else,

 // and a logical operator

 #include <iostream.h>

 void main()

 {

    int numCusts;

    float totalSales;


    cout << "How many customers were in yesterday? ";

    cin >> numCusts;


    cout << "What were the total sales? ";

    cin >> totalSales;


    // A simple if

    if (numCusts > 25)

      { cout << "Order more snacks for tomorrow." << endl; }


    // An if-else

    if (totalSales >= 2000.00)

      { cout << "Reorder stock." << endl;

        cout << "Give sales staff a raise." << endl;

      }

    else

     { cout << "Replace the sales staff." << endl; }


    // An if with a logical test

    if ((numCusts >= 50) && (totalSales >= 5000.00))

      { cout << "Take a day off!" << endl;

        cout << "Remodel the store." << endl;

      }

    return;

 }

=========================


C++ From Year 1995 File From "J"

 // Filename : JellyB1.CPP

// Demonstration of pointer scope issues

//

#include <iostream.h>

#include <string.h>


struct JellyBean

  {

    int i;

    int j;

    char* str;

  };

  

void main()

  {

    JellyBean red = {1,2,0};

    red.str = new char[30];

    

    strcpy(red.str,"A red jelly bean");

    

    JellyBean anotherRed = red;

    

    // But now both red.str and anotherRed

    // point to str

    

    cout << anotherRed.i << ", "

         << anotherRed.j << ", "

         << anotherRed.str;


    strcpy(red.str,"A blue jelly bean");

    

    // Is this a surprise? 

    cout << endl << "After assignment to red:" << endl;

    cout << anotherRed.i << ", "

         << anotherRed.j << ", "

         << anotherRed.str;

    

    delete [] red.str;

    red.str = 0; // Good practise

    // What does anotherRed.str equal? 

    //

    // Another small experiement

    //           

    {

      char newString[] =        "Oh! no! not the comfy chair!           ";

      red.str = newString;

    } // newString no longer exists

    {

      char anotherNewString[] = "No one expects the Spanish Inquisition!";

      cout << endl << red.str;  // red.str should point to newString???

    }

  }    

C++ From Year 1995 File From "I"

 // Filename: IFELSETV.CPP

// This program uses embedded if-else statements to print

// a message for the user. The printed message corresponds

// to the user's favorite television channel.

#include <iostream.h>

void main()

{

  int channel;


  cout << "In this town, there are five non-cable television ";

  cout << "channels." << endl;

  cout << "What is your favorite (2, 4, 6, 8, or 11)? ";

  cin >> channel;

  cout << endl << endl;   // Output two blank lines


  // Use an embedded if to print appropriate messages

  if (channel == 2)

    { cout << "Channel 2 got top ratings last week!"; }

  else

    if (channel == 4)

     { cout << "Channel 4 shows the most news!"; }

       else

         if (channel == 6)

           { cout << "Channel 6 shows old movies!"; }

         else

           if (channel == 8)

             { cout << "Channel 8 covers many local events!"; }

           else

             if (channel == 11)

               { cout << "Channel 11 is public broadcasting!"; }

             else   // The logic gets here only if the

                    // user entered an incorrect channel

               { cout << "Channel " << channel

                      << " does not exist; it must be cable."; }


  cout << endl << endl << "Happy watching!";

  return;

}

==================================

  // Filename: INCDEC.CPP

  // Uses increment and decrement

  #include <iostream.h>

  void main()

  {

    int age;

    int lastYear, nextYear;


    cout << "How old are you? ";

    cin >> age;


    lastYear = age;

    nextYear = age;


    cout << "Wow, you're a year older than last year ("

         << --lastYear << ")" << endl;

    cout << "and you'll be " << ++nextYear

         << " next year."  << endl;


    return;

  }

========================

// Filename: INITS2.CPP

// Makes sure that the user enters two initials

#include <ctype.h>

#include <iostream.h>


void main()

{

  char f, l;

  cout << "What is your first initial? ";

  cin >> f;

  cin.ignore(80,'\n');  // Discard the newline

  if (!isalpha(f))

    { cout << "That's not an initial!" << endl;

      return;

    }


  cout << "What is your last initial? ";

  cin >> l;

  if (!isalpha(l))

    { cout << "That's not an initial!" << endl;

      return;

    }

  // Converts to uppercase if needed

  f = toupper(f);

  l = toupper(l);

  cout << "Here are your initials: " << f << l << "" << endl;

  return;

}

=========================

// Filename: INTCHAR.CPP

 // Mixing integers and characters

 #include <iostream.h>

 void main()

 {

   int i, j, k;   // Define 3 integers

   char c, d, e;  // Define 3 characters


   // Mix the data

   i = 'A';   // Stores 65 in i

   j = 'B';   // Stores 66 in j

   k = 'C';   // Stores 67 in k


   c = 88;    // Stores 'X' in c

   d = 89;    // Stores 'Y' in d

   e = 90;    // Stores 'Z' in e


   cout << i << ", " << j << ", " << k << endl;

   cout << c << ", " << d << ", " << e << endl;

   return;

 }

==============================

// Filename: INTDIV.CPP

// Computes integer division

#include <iostream.h>

void main()

{

  int people, events;

  float avgEv;


  cout << "How many people will attend? ";

  cin >> people;

  cout << "How many events are scheduled? ";

  cin >> events;


  // Compute the average number of people per event

  avgEv = people / events;   // The integer division ensures

                             // that the fractional part of

                             // the answer is discarded

  cout << "There will be an average of " << avgEv

       << " people per event." << endl;

  return;

}

==============================

// Filename: INTFIVE.CPP

 // Compute five periods of interest

 #include <iostream.h>

 void main()

 {

   float intRate;     // Interest rate per period

   float principal;   // Loan amount


   cout << "Welcome to loan central!" << endl;  // Title

   cout << "------------------------" << endl << endl;


   cout << "How much was the loan for? ";

   cin >> principal;


   cout << "What is the period interest rate (i.e., .03 for 3%)? ";

   cin >> intRate;


   cout << "Here is the total owed after five periods" << endl;

   cout << "(Assuming no payment is made)" << endl;


   principal *= (1 + intRate);    // First period interest

   principal *= (1 + intRate);

   principal *= (1 + intRate);

   principal *= (1 + intRate);

   principal *= (1 + intRate);    // Fifth period interest


   cout.precision(2);

   cout.setf(ios::fixed);         // Ensure two decimal places

   cout.setf(ios::showpoint);

   cout << "$" << principal

        << " total amount owed after five periods." << endl;

   return;

 }

===========================

// Filename: INTFIVE2.CPP

// Compute five periods of interest

// Print the principal after each period

#include <iostream.h>


void main()

{

  float intRate;     // Interest rate per period

  float principal;   // Loan amount


  cout << "Welcome to loan central!" << endl;  // Title

  cout << "------------------------" << endl  << endl;


  cout << "How much was the loan for? ";

  cin >> principal;


  cout << "What is the period interest rate (i.e., .03 for 3%)? ";

  cin >> intRate;


  cout.precision(2);

  cout.setf(ios::fixed);

  cout.setf(ios::showpoint);

  principal *= (1 + intRate);    // 1st period interest

  cout << "Principal after 1 period: " << principal <<  endl;

  principal *= (1 + intRate);

  cout << "Principal after 1 period: " << principal <<  endl;

  principal *= (1 + intRate);

  cout << "Principal after 1 period: " << principal <<  endl;

  principal *= (1 + intRate);

  cout << "Principal after 1 period: " << principal <<  endl;

  principal *= (1 + intRate);    // 5th period interest


  cout << "Here is the total owed after five periods" << endl;

  cout << "(Assuming no payment is made)"  << endl;


  cout << "$" << principal << " total amount owed after five periods." << endl;

  return;

}

============================

// Filename: INVENT2V.CPP

 #include <iostream.h>

 void main()

 {


   // Define the two inventory variables

   float price;

   char descrip[25];


   cout << "What is the item's description? ";

   cin.getline(descrip, 25);


   cout << "What is the item's price? ";

   cin >> price;


   cout << endl << endl << "Here is the item: " << endl;

   cout << "  Description: " << descrip;


   cout.precision(2);

   cout.setf(ios::fixed);

   cout.setf(ios::showpoint);

   cout << "  Price: " << price << endl;

   return;

 }

=======================================

// Filename: INVSRCH.CPP

// Demonstrates the sequential parallel array searching

// technique. An inventory ID number is asked for. If

// the ID is found in the arrays, that product's

// inventory data is displayed for the user.

#include <iostream.h>


int GetKey();

int SearchInv(int keyVal, int prodID[]);

void PrintData(int foundSub, int prodID[], int numItems[],

               float price[], int reorder[]);


const int INV = 10; // Products in this sample array


void main()

{


  // First, initialize a few sample elements

  // Product IDs

  int prodID[INV] = {32, 45, 76, 10, 94,

                     52, 27, 29, 87, 60};

  // Number of each product currently in the inventory

  int numItems[INV] = {6, 2, 1, 0, 8,

                       2, 4, 7, 9, 3};

  // Price of each product

  float price[INV] = {5.43, 6.78, 8.64, 3.32, 1.92,

                      7.03, 9.87, 7.65, 4.63, 2.38};

  // Reorder levels

  int reorder[INV] = {5, 4, 1, 3, 5,

                      6, 2, 1, 1, 4};

  int keyVal, foundSub;


  // The program's primary logic begins here

  keyVal = GetKey();   // Ask the user for an ID

  foundSub = SearchInv(keyVal, prodID);   // Search the inventory

  if (foundSub == -99)

    { 

      cout << "That product is not in the inventory.";

      return;

    }

  // Here only if the item was found

  PrintData(foundSub, prodID, numItems, price, reorder);

  return;

}

//**********************************************************

int GetKey()

{

  // Ask the user for an ID

  int keyVal;

  cout << "** Inventory Search Program **" << endl;

  cout << endl << endl << "Enter a product ID: ";

  cin >> keyVal;

  return (keyVal);

}

//**********************************************************

int SearchInv(int keyVal, int prodID[])

{

  // Search the ID array and return the subscript of

  // the found product, or return -99 if not found

  int foundSub = -99;

  int c;

  for (c = 0; c < INV; c++)

    { 

      if (keyVal == prodID[c])

        { 

          foundSub = c;

          break;

        }

    }

  // The -99 will still be in foundSub

  // if the search failed

  return (foundSub);

}

//**********************************************************

void PrintData(int foundSub, int prodID[], int numItems[],

       float price[], int reorder[])

{

  // Print the data from the matching parallel arrays

  cout.precision(2);

  cout.setf(ios::showpoint);

  cout.setf(ios::fixed);

  cout << endl << "Product ID: " << prodID[foundSub]

       << "\tNumber in stock: "

       << numItems[foundSub] << endl;

  cout << "Price: $" << price[foundSub] << "\tReorder: "

       << reorder[foundSub] << endl;

  return;

}

===================================

// Filename: INVSRCH2.CPP

// Demonstrates the sequential parallel array searching

// technique. An inventory ID number is asked for. If

// the ID is found in the arrays, that product's

// inventory data is displayed for the user.


#include <iostream.h>


int getKey(void);

int searchInv(int keyVal, int prodID[]);

void prData(int foundSub, int prodID[], int numItems[],

       float price[], int reorder[]);


const int INV = 10;   // Products in this sample array


void main()

{

  // First, initialize a few sample elements

  // Product IDs

  int prodID[INV] = {32, 45, 76, 10, 94,

                     52, 27, 29, 87, 60};

  // Number of each product currently in the inventory

  int numItems[INV] = {6, 2, 1, 0, 8,

                       2, 4, 7, 9, 3};

  // Price of each product

  float price[INV] = {5.43, 6.78, 8.64, 3.32, 1.92,

                      7.03, 9.87, 7.65, 4.63, 2.38};

  // Reorder levels

  int reorder[INV] = {5, 4, 1, 3, 5,

                      6, 2, 1, 1, 4};

  int keyVal, foundSub;


  // The program's primary logic begins here

  do

  {

    keyVal = getKey();   // Ask the user for an ID

    if (keyVal == -99)

      { break; }

    foundSub = searchInv(keyVal, prodID);   // Search the

                                            // inventory

    if (foundSub == -99)

      { cout << "That product is not in the inventory.";

        cout << endl << endl << "Press any key to continue...";


        cin.ignore(80,'\n');

        continue;   // Loop again

      }

    // Here only if the item was found

    prData(foundSub, prodID, numItems, price, reorder);

    cout << endl << endl << "Press any key to continue...";

    cin.ignore(80,'\n');

  } while (keyVal != -99);

  return;

}

//**********************************************************

int getKey(void)

{

  // Ask the user for an ID

  int keyVal;

  cout << "** Inventory Search Program **" << endl;

  cout << endl << endl << "Enter a product ID (-99 to quit): ";

  cin >> keyVal;

  return (keyVal);

}

//**********************************************************

int searchInv(int keyVal, int prodID[])

{

  // Search the ID array and return the subscript of

  // the found product. Return -99 if not found.

  int foundSub = -99;

  int c;

  for (c = 0; c < INV; c++)

    { if (keyVal == prodID[c])

      { foundSub = c;

        break;

      }

    }

  // The -99 will still be in foundSub

  // if the search failed

  return (foundSub);

}

//**********************************************************

void prData(int foundSub, int prodID[], int numItems[],

       float price[], int reorder[])

{

  // Print the data from the matching parallel arrays

  cout.precision(2);

  cout.setf(ios::showpoint);

  cout.setf(ios::fixed);

  cout << endl << "Product ID: " << prodID[foundSub]

       << "\tNumber in stock: " << numItems[foundSub]

       << endl;

  cout << "Price: $" << price[foundSub]

       << "\tReorder: " << reorder[foundSub] << endl;

  return;

}

==================================

// Filename: IOFIX.CPP

// Makes a copy of a file

#include <fstream.h>


void main()

{

  ifstream inFp;

  ofstream outFp;

  char inFilename[25];   // Holds original filename

  char outFilename[25];   // Holds backup filename

  char inChar;   // Inputs character


  cout << "What is the name of the file you want to"

       << " back up? ";

  cin >> inFilename;

  cout << "What is the name of the file ";

  cout << "you want to copy " << inFilename << " to? ";

  cin >> outFilename;

  inFp.open(inFilename, ios::in);


  if (!inFp)

  {

    cout << endl << endl << "*** " << inFilename 

       << " does not exist ***";

    return;   // Exits program

  }

  outFp.open(outFilename, ios::out);

  if (!outFp)

  {

    cout << endl << endl << "*** Error opening " 

       << inFilename << " ***" << endl;

    return;   // Exits program

  }

  cout << endl << "Copying..." << endl;   // Waiting message


  //

  // The inserted code follows:

  while (inFp.get(inChar))

    { outFp << inChar;

    }

  //

  // The program continues


  cout << endl << "The file is copied." << endl;

  inFp.close();

  outFp.close();

  return;

}

===============================

// File name IOSTEST.CPP

// A demonstration of file streams

// which shows that we already know

// how to use files.


#include <fstream.h> // also includes iostream.h


void main()

  {

    float f;

    char text[100]; 

    // Open a file for output

    ofstream out("hello.txt"); 

    cout << "Please enter a line of text: ";

    // Get some text from the screen

    cin.getline(text,30);    

    // Make sure the file is open...

    if (out.is_open())

        {

          // Output the input

          out << text;       

          // Output a literal

          out << "The world is an orange";

          // Output a number

          f = 33.5F;

          out << f;        

          // Close the file so data is avaliable

          out.close();

        }

    cout << "Here is the file:" << endl;

    // Open the file for input

    ifstream in("hello.txt");               

    // Read file item by item (white space delimits)

    while (in.is_open() && !in.eof())

      {

        in >> text;

        cout << text << endl;

      }

    // Reposition to the start by closing and opening

    in.close();

    in.open("hello.txt");

        

    // Get the contents as text

    if (in)  // same as is_open()

      {

        in.getline(text,100);

        cout << endl << endl;

        cout << "Here is the file:" << endl;

        cout << text;

      }

  }     

======================================================


C++ From Year 1995 File From "H"

 // Filename: HOTELIF.CPP

  // Determines a hotel price

  #include <iostream.h>

  void main()

  {

    char ans;

    int numNights;

    float rackRate = 67.50;

    float discRate = 57.65;

    float totalCost = 0.0;


    cout << "How many nights did the customer stay? ";

    cin >> numNights;


    cout << "Has the customer stayed here before (Y/N)? ";

    cin >> ans;


    if (ans == 'Y')

      { totalCost = discRate * numNights; }


    if (ans == 'N')

      { totalCost = rackRate * numNights; }


    cout.setf(ios::showpoint);

    cout.setf(ios::fixed);

    cout.precision(2);

    cout << "The total cost is $" << totalCost << endl;


    return;

  }


C++ From Year 1995 File From "G"

 // Filename: GB.CPP

// Determines whether the user typed a G or a B.

#include <iostream.h>

// toupper is in ctype.h

#include <ctype.h>


void main()

{

  char ans;   // Holds user's response


  cout << "Are you a girl or a boy (G/B)? ";

  cin >> ans;   // Gets answer


  cout << endl;


  ans = toupper(ans);   // Converts answer to uppercase

  switch (ans)

  {   case ('G'): { cout << "You look pretty today!" << endl;

                    break; }

      case ('B'): { cout << "You look handsome today!" << endl;

                    break; }

      default :   { cout << "Your answer makes no sense!" << endl;

                    break; }

  }

  return;

}

=======================

// Filename: GCH1.CPP

// Uses get() and put() for input and output


#include <fstream.h>


void main()

{

   int ctr;   // for loop counter

  char letters[5];   // Holds five input characters. No

                     // room is needed for the null zero

                     // because this array will never be

                     // treated as a string.

  cout << "Please type five letters..." << endl;

  for (ctr = 0; ctr < 5; ctr++)

  {

    letters[ctr] = cin.get();   // Adds input to array

  }

 

  for (ctr = 0; ctr < 5; ctr++)   // Prints them to printer

  {

    cout.put(letters[ ctr ]);

  }

  return;

}

======================

// Filename: GETL.CPP

#include <iostream.h>

void main()

{

  char city[15];

  cout << "Where are you from? ";

  cin.getline(city, 15);

  cout << "So you are from " << city << endl;

  return;

}

=========================

// Filename: GETS.CPP

// Gets a string from the keyboard into a character array

#include <iostream.h>


void main()

{

  char str[81];   // Reserves space for up to 80 characters

                  // and the null zero


  cout << "What is your full name? ";

  cin.get(str, 80);


  cout << "Thank you, " << str << ", for answering me.";

  return;

}

============================

// Filename: GOTO.CPP

// Uses goto to print messages in a strange order

#include <iostream.h>

void main()

{


  goto Larry;

Final:

  cout << "What a stooge of a program!" << endl;

  goto EndIt;


Moe:

  cout << "Moe is here!" << endl;

  goto Curly;


Larry:

  cout << "Larry is here!" << endl;

  goto Moe;


Curly:

  cout << "Curly is here!" << endl;

  goto Final;


EndIt:

  return;

}

===========================


C++ From Year 1995 File From "F"

 // Filename: FIXCHNBG.CPP

// Stores the alphabet in a file, reads two letters from it,

// and changes those letters to x


#include <fstream.h>


void main()

{

  fstream fp;

  char ch;   // Holds A through Z


  // Opens in update mode so that you can

  // read file after writing to it

  fp.open("alph.txt", ios::in | ios::out);

  if (!fp)

  {

    cout << "*** Error opening file ***";

    return;

  }

  for (ch = 'A'; ch <= 'Z'; ch++)

    { fp << ch; }   // Writes letters

  fp.seekg(8L, ios::beg);  // Skips eight letters, points to I

  fp >> ch;

  // Changes the I to an x

  fp.seekg(-1L, ios::cur);

  fp << 'x';

  cout << "The first character is " << ch << endl;

  fp.seekg(16L, ios::beg);   // Skips 16 letters, points to Q

  fp >> ch;

  cout << "The second character is " << ch << endl;

                             // Changes the Q to an x

  fp.seekg(-1L, ios::cur);

  fp << 'x';

  fp.close();

  return;

}

===========================
// Filename: FLOTARPT.CPP
// Defines a floating-point array and then
// accesses elements from the array using
// pointer notation
#include <iostream.h>

void main()
{
  float ara[6] = {11.1, 22.2, 33.3, 44.4, 55.5, 66.6};
  int ctr;   // for-loop counter

  // First, print the array using subscripts
  cout << "Here is the array using subscripts:" << endl;
  cout.precision(1);
  cout.setf(ios::showpoint);
  cout.setf(ios::fixed);
  for (ctr = 0; ctr < 6; ctr++)
    { cout << ara[ctr] << ' '; }

  // Print the array using simple pointer notation
  cout << endl << endl 
       << "Here is the array using pointers:" << endl;
  for (ctr = 0; ctr < 6; ctr++)
    { cout << *(ara + ctr) << ' '; }

  // You can even combine pointer and array notation!
  cout << endl << endl 
       << "Here is the array using a combination:" << endl;
  cout << (ara + 0)[0] << ' ';  // ara[0]
  cout << (ara + 1)[0] << ' ';  // ara[1]
  cout << (ara + 0)[2] << ' ';  // ara[2]
  cout << (ara + 0)[3] << ' ';  // ara[3]
  cout << (ara + 3)[1] << ' ';  // ara[4]
  cout << (ara + 2)[3] << ' ';  // ara[5]
  return;
}
======================
// Filename: FORAVG.CPP
// A for loop asks the user for five values.
// As the user enters each value, a compound
// assignment statement adds the values.
// After all five values have been entered and
// the loop ends, the program prints an average.
#include <iostream.h>
void main()
 {
   float value, avg;
   float total = 0;

   cout << endl << "** An Average Program **"
        << endl << endl;

   // Loop five times
   for (int count = 0; count < 5; count++)
     { 
       cout << "What is the next value? ";
       cin >> value;
       total += value;   // Add to the total variable
     }

   // Now, compute and print the average
   avg = total / 5.0F;
   cout.precision(1);
   cout.setf(ios::fixed);
   cout.setf(ios::showpoint);
   cout << endl << "The average of your values is " 
        << avg << endl;
   return;
 }
=======================
// Filename: FORAVG2.CPP
// A for loop asks the user for values as determined by the
// #define value. As the user enters each value, a compound
// assignment statement adds the values. After the loop ends
// and all three values are entered, the program prints an average.
#include <iostream.h>

void main()
{
  const int NUM = 5;  // A constant variable that can't change
  int count;          // The for loop's control variable
  float value, avg;
  float total = 0;

  cout << "** An Average Program **" << endl << endl;

  // Loop num times
  for (count=0; count<NUM; count++)
    { cout << "What is the next value? ";
      cin >> value;
      total += value;    // Add to the total variable
    }

  // Now, compute and print the average
  avg = total / (float)NUM;
  cout << endl << "The average of your values is " << avg << endl;
  return;
}
===================
// Filename: FORBREAK.CPP
// Prints a dog's name 10 times
// (or less if the user dictates)
#include <iostream.h>
void main()
{
  char ans;         // Will hold a Y or N answer
  int count;        // The loop control variable
  char dName[25];   // Will hold the dog's name

  cout << "What is your dog's name? ";
  cin >> dName;

  cout << "I'll now print the name ten times (maybe)..." << endl;

  for (count = 0; count < 10; count++)
    { cout << dName << endl;
      cout << "Do you want to see the name again (Y/N)? ";
      cin >> ans;
      if ((ans == 'N') || (ans == 'n'))
        { 
          break;  // Terminate early
        }  
    }   // Iterate again if not broken out of the loop

  cout << "That's a nice dog!";
  return;
}

C++ From Year 1995 File From "E"

 // Filename:  EDIT.CPP

#include <iostream.h>

void main()

{

cout << "Visual C++ is easy!";

}

=======================================

// Filename: ERAS.CPP

// Erases the file specified by the user


#include <stdio.h>

#include <iostream.h>


void main()

{

  char filename[255];


  cout << "What is the filename you want me to erase? ";

  cin >> filename;

  if (remove(filename))

    cout << "*** I could not remove the file ***"; 

  else

    cout << "The file " << filename

         << " is now removed";

}

====================

// Filename: EVNTOODD.CPP

// Changes the user's value to the next-highest odd number

#include <iostream.h>

void main()

 {

   int num;


   cout << "Enter an even number: ";

   cin >> num;


   num |= 1;   // Turn on the rightmost bit position

   cout << "The next-highest value is " << num << endl;


   return;

 }

============================

// Filename: EXPRESS.CPP

// Computing expressions with C++

#include <iostream.h>


void main()

{

  int ans1, ans2, ans3;


  ans1 = 2 * 3 + 3 * 2;

  cout << "The first answer is " << ans1 << endl;

  ans2 = 20 + 20 / (5 + 5) % 2;

  cout << "The second answer is " << ans2 << endl;

  ans3 = ((2 + 3) + 6 * (3 + (4 - 2))) + 3;

  cout << "The third answer is " << ans3 << endl;

  return;

}


C++ From Year 1995 File From "D"

 // Filename: DATECHK.CPP

// Demonstrates a complete OOP program with class data

// Add simply error-checking to the member function code

// so that reasonable values are assigned to the date.

#include <iostream.h>


class Date {

   int day;

   int month;

   int year;

public:    // Everything that follows is accessible by main()

   void prDate();        // Member functions

   void setDay(int d);

   void setMonth(int m);

   void setYear(int y);

};


void Date::prDate()      // :: Tells C++ the owner class

{

   cout << "Date: " << day << "/" << month << "/"

        << year << "" << endl;

}

void Date::setDay(int d)

{

   if (d <= 31)

     { day = d; }

   else

     { cout << endl << "The day cannot be " << d << "!" << endl; }

}


void Date::setMonth(int m)

{

   if (m <= 12)

     { month = m; }

   else

     { cout << endl << "The month cannot be " << m << "!" << endl; }

}


void Date::setYear(int y)

{

   if (y >= 90)

     { year = y; }

   else

     { cout << endl << "The year cannot be " << y << "!" << endl; }

}


void main()

{

   Date today;         // Define a new active class variable

   // today.day = 20 is NOT possible!!! You must initialize

   // the data can only be initialized through member functions

   today.setDay(20);     // Initialize the day

   today.setMonth(6);    // Initialize the month

   today.setYear(1994);  // Initialize the year

   today.prDate();       // Print the date (You could'nt print the

                         // date's values via the dot operator!)

   return;

}



=========================

// Filename: DEFPNTS.CPP

// Defines several variables and pointers to those variables

#include <iostream.h>


void main()

{

  int     i1 = 14;    // Define and initialize an integer

  int*    ip1;        // Define a pointer to an integer

  int     i2 = 20;

  int*    ip2 = &i2;  // Define and initialize the pointer

  float   f = 92.345;

  float*  fp = &f;

  double  d;

  double* dp;


  ip1 = &i1;

  

  cout.precision(3);

  cout.setf(ios::showpoint);

  cout.setf(ios::fixed);

  

  cout << "i1 is " << i1 << " and *ip1 is also "

       << *ip1 << endl;

  

  cout << "i2 is " << i2 << " and *ip2 is also "

       << *ip2 << endl;

  

  cout << "f is " << f << " and *fp is also "

       << *fp << endl;

  

  *fp = 1010.10;

  

  cout << "After changing f through fp, " << endl;

  cout << "f is now " << f << " and *fp is also "

       << *fp << endl;                           

       

  dp = &d;

  *dp = 83949443.54333;   // Change dp

  

  cout << "d is now " << d << " and *dp is also "

       << *dp << endl;

  return;

}

========================

// Filename: DISSECT.CPP

// Simple program for you to analyze


#include <iostream.h>


void main()

{

  int age, weight;   // These lines define four variables

  char initial;

  double salary;


  age = 13;   // Assigns an integer literal to age

  weight = age * 6;   // Assigns a weight based on a formula

  initial = 'D';      // All character literals are

                      // enclosed in single quotes

  salary = 200.50;    // salary requires a floating-point

                      // value because it was defined to

                      // be a floating-point

  salary = salary * 2.5;   // Changes what was in salary


  // Next line sends the values of the variables to the screen

  cout << age << ", " << weight << ", " << initial

       << ", " << salary;


}

===============================

// Filename: DOUSRAGE.CPP

// Uses a do-while loop to get an age from the user

#include <iostream.h>

void main()

{

  int age;


  // In the previous listing, two extra lines went here

  do

    { cout << "How old are you? ";   // Get the age

      cin >> age;

      if ((age < 5) || (age > 110))

        { cout << "I'm not sure that I believe you are "

               << age << endl;

          cout << "Try again..." << endl << endl; }

    } while ((age < 5) || (age > 110));   // Quit after good input


  // The program continues if the user entered a reasonable age

  if (age < 16)

    { cout << "Your curfew is at 11:30 pm" << endl;

      cout << "Have fun!" << endl;

    }

  else

    {

      cout << "You're old enough to drive, so be careful ";

      cout << "out there!" << endl;

    }

  return;

}

==============================


C++ From Year 1995 File From "C"

 // Filename: CFIRST.CPP

// Program displays a message on-screen

#include <iostream.h>

void main()

{

   cout << "I will be a C++ expert!";

}

=======================

// Filename: CH1.CPP

// Introduces get() and put()


#include <fstream.h>


void main()

{

  char  in_char;   // Holds incoming initial

  char first, last;   // Holds converted first and last initial


  cout << "What is your first name initial? ";

  cin.get(in_char);   // Waits for first initial

  first = in_char;

  cin.get(in_char);   // Ignores newline

  cout << "What is your last name initial? ";

  cin.get(in_char);   // Waits for last initial

  last = in_char;

  cin.get(in_char);   // Ignores newline

  cout << endl << "Here they are: " << endl;

  cout.put(first);

  cout.put(last);

  return;

}

========================

// Filename: CHANGBUG.CPP

// Stores the alphabet in a file, reads two letters from it,

// and changes those letters to x


#include <fstream.h>



void main()

{

  fstream fp;

  char ch;   // Holds A through Z


  // Opens in update mode so that you can

  // read file after writing to it

  fp.open("alph.txt", ios::in | ios::out);

  if (!fp)

  {

    cout << endl << "*** Error opening file ***" << endl;

    return;

  }

  for (ch = 'A'; ch <= 'Z'; ch++)

    { fp << ch; }   // Writes letters

  fp.seekg(8L, ios::beg);  // Skips eight letters, points to I

  fp >> ch;

  // Changes the I to an x

  fp.seekg(-2L, ios::cur);

  fp << 'x';

  cout << "The first character is " << ch << endl;

  fp.seekg(16L, ios::beg);   // Skips 16 letters, points to Q

  fp >> ch;

  cout << "The second character is " << ch << endl;

  // Changes the Q to an x

  fp.seekg(-2L, ios::cur);

  fp << 'x';

  fp.close();

}

=======================

// Filename: CHARFUNS.CPP

// Uses character arrays and character pointers

#include <iostream.h>

#include <string.h>


void main()

{

  char c;


  char * cpt0;   // A stand-alone character pointer

  char * cpt5 = "abcd";           // Points to 5 bytes

  char * cpt12 = "Programming";   // Points to 12 bytes

  char   ara27[27];               // Points to 27 bytes

  char * cpt27 = ara27;           // Points to 27 bytes


  cpt0 = "cpt0 is pointing to this string";

  cout << cpt0;   // No problem

  cpt0 = "A new string for cpt0";   // Still no problem

  cout << endl << cpt0 << endl;

  // You couldn't

  // strcpy(cpt0, "This is a string for cpt0 that is too long")

  // though!


  cout << "Please type your name (up to 12 characters): ";

  cin.get(cpt12, 12);   // Okay because of get() 12-char limit

  cout << "You typed " << cpt12 << endl << endl;


  // cin.get(cpt5, 12) wouldn't work either because

  // all characters after the fifth one would overwrite

  // memory not pointed to by cpt5


  // Fill the 27-character array

  for (c = 'A'; c <= 'Z'; c++)

    { ara27[c - 65] = c;  }   // ASCII A is equivalent to decimal 65

  ara27[26] = '\0';;

  

  strcpy(cpt27, ara27);   // Okay because they point to

                          // the same number of bytes

  // strcpy(cpt12, ara27) would NOT be okay

  cout << "cpt27 contains: " << cpt27;

  return;

}

============================

// Filename: CITYNAME.CPP

// Stores and prints a list of city names

#include <iostream.h>


void main()

{

  int ctr;


  char * cities[5] = {"San Diego", "Miami", "New York",

                      "Oklahoma City", "St. Louis"};


  // Print the cities

  // Anywhere a character array can appear, so can the

  // elements from the cities array of pointers

  cout << "Here are the stored cities:" << endl;

  for (ctr = 0; ctr < 5; ctr++)

    { cout << cities[ctr] << endl; }

  cout << endl;


  // Change the cities with literals

  // These assignments store the address of

  // the string literals in the elements

  cities[0] = "Tulsa";

  cities[1] = "Boston";

  cities[2] = "Indianapolis";

  cities[3] = "Las Vegas";

  cities[4] = "Dallas";


  // Print the cities again using pointer notation

  cout << endl << "After changing the pointers:" << endl;

  for (ctr = 0; ctr < 5; ctr++)

    { cout << *(cities + ctr) << endl ; }

  cout << endl;


  return;

}

==========================

// Filename: CLASSPGM.CPP

// Demonstrates a complete OOP program with class data


#include <iostream.h>


class Date {

   int day;

   int month;

   int year;

public:    // Everything that follows is accessible by main()

   void prDate();        // Member functions

   void setDay(int d);

   void setMonth(int m);

   void setYear(int y);

};


void Date::prDate()      // :: Tells C++ the owner class

{

   cout << "Date: " << day << "/" << month << "/"

        << year << endl;

}


void Date::setDay(int d)

{

   day = d;

}


void Date::setMonth(int m)

{

   month = m;

}


void Date::setYear(int y)

{

   year = y;

}


void main()

{


   Date today;         // Define a new active class variable

   // today.day = 20 is NOT possible!!! You must initialize

   // the data can only be initialized through member functions

   today.setDay(20);     // Initialize the day

   today.setMonth(6);    // Initialize the month

   today.setYear(1994);  // Initialize the year

   today.prDate();       // Print the date (You couldn't print the

                         // date's values via the dot operator!)

   return;

}

=============================

// Filename: COMAVGE.CPP

// Program to compute the average of three values

#include <iostream.h>

void main()

{

  double g1, g2, g3;   // Variables to hold student grades


  cout << "What grade did the first student get? ";

  cin >> g1;


  cout << "What grade did the second student get? ";

  cin >> g2;


  cout << "What grade did the third student get? ";

  cin >> g3;


  double avg = (g1 + g2 + g3) / 3.0;   // Computes average


  cout << "The student average is " << avg;  // Prints average

  return;

}

=========================

// File name: CONDEST.CPP

// Shows construction and destruction

// of objects and simple memory management

//

#include <iostream.h>

#include <string.h>


class Name

  {

    public:   

      // Constructor

      Name();       

      // Destructor

      ~Name();  

      void SetName(const char * newName);

      const char * GetName() const;

    private:

      char * name;

  };

void main()

  {

    cout << "-- First line of main() --" << endl;

    Name firstName;

    firstName.SetName("firstName");

    Name * secondName = new Name;

    secondName->SetName("secondName");

    cout << "-- Before block --" << endl;

    // New block

      {

        cout << "-- First line of block --" << endl;

        Name thirdName;

        Name fourthName;

        thirdName.SetName("thirdName");   

        cout << "-------------------" << endl;

        cout << "Contents of objects" << endl;

        cout << firstName.GetName() << endl;

        cout << secondName->GetName() << endl;

        cout << thirdName.GetName() << endl;

        cout << fourthName.GetName() << endl;

        cout << "-------------------" << endl ;

        cout << "-- Last line of block --" << endl;

      }  // Block ends - third & fourth name destroyed

    cout << "-- After block --" << endl;

    delete secondName;

    cout << "-- Last line of main() --" << endl;

  }      // firstName goes;  

//*********************************************************

//

// Name  class function definitions

//


// Constructor        

Name::Name()

  {

    cout << "Constructor called" << endl;

    name = 0;

  }           


// Destructor

Name::~Name()

  {

    cout << "Destructor called ";

    cout << "name is " << GetName() << endl;

    delete name; // Delete on zero pointer is safe

  }          

  

// Member function to store a name                    

//

void Name::SetName(const char* newName)

  {

     // First, remove any name that might already exist

     // Use zero pointer to inidicate no name stored

     // C++ will not destroy storage on a zero pointer

     // "if (name)"

     delete [] name;                                    

     // Create new storage

     name = new char[strlen(newName) + 1]; // add 1 for

                                           // terminator

     strcpy(name,newName);  // Copy data into new name

  }


// Member function to get the stored name

// Coded to always return a safe value

const char * Name::GetName() const

  {

    if (name)

      return name;

    else

      return "No name exists";

  }

    ====================================

 // Filename: CONDIT.CPP

 // Finds the minimum and maximum values

 // from the user's entered values

 #include <iostream.h>

 void main()

 {

   int val1, val2, min, max;


   cout << "Enter a value: ";

   cin >> val1;


   cout << "Enter another value: ";

   cin >> val2;


   if (val1 < val2)

      { min = val1;

        max = val2; }

   else

      { max = val1;

        min = val2; }


   cout << endl << "Using if-else, the minimum is " 

        << min << " and the maximum is " << max << endl;


   min = (val1 < val2) ? val1 : val2;

   max = (val2 > val1) ? val2 : val1;


   cout << endl << "Using ?:, the minimum is " 

        << min << " and the maximum is " << max << endl;

   return;

 }

=========================

// Filename: CONTACT.CPP

// Allow the display and entry of contacts

//

#include <iostream.h>


struct Contact

  {

     char name[50];

     int  age;

     char phoneNo[15];

  };                         

  

// Maximum number of contacts

const int MAXCONTACTS = 10;


// Prototypes

int AddContact(Contact& contact);

void DisplayContact(const Contact& contact);  

void DisplayAllContacts(const Contact contacts[MAXCONTACTS],int count);


void main()  

  {

    Contact contacts[MAXCONTACTS];

    int count = 0;

    while( count < MAXCONTACTS )// while more room

      {

         if (AddContact(contacts[count]))

           count++;

         else

           break;

      }

    DisplayAllContacts(contacts,count);

  }                                         

//

// DisplayContact displays a single name

//

void DisplayContact(const Contact& contact)  

  {

    cout << endl;

    cout << "Name    : " << contact.name << endl;

    cout << "Age     : " << contact.age << endl;

    cout << "phone no: " << contact.phoneNo << endl;

    cout << endl;

  }

//

// DisplayAllContacts calls DisplayContact to show

// all entered names

//

void DisplayAllContacts(const Contact contacts[MAXCONTACTS],int count)

  {

    for (int i = 0; i < count; i++)

      {

        DisplayContact(contacts[i]);

      }    

  } 

//

// Add contact asks for one contact

//

int AddContact(Contact& contact)

  {

    char answer;

    cout << "Do you want to add a contact [Y]es/[N]o: ";

    cin >> answer;

    cin.ignore(); // skip rubbish

    

    if (answer == 'y' || answer == 'Y')

      {          

        cout << "Name: ";

        cin.getline(contact.name,30);

        cout << "Phone no: ";

        cin.getline(contact.phoneNo,15);

        cout << "Age ";

        cin >> contact.age;

        cin.ignore();

        return 1;   // Added name ok

      }

    else

      return 0;     // Did not add name

   }

==================================

// Filename: CONTACTO.CPP

// Allow the display and entry of contacts

// using OOP techniques

//

#include <iostream.h>


class Contact

  {

    public:          

     char name[50];

     int  age;

     char phoneNo[15];

      

     // Member function declarations (prototypes)

     void AddContact();

     void DisplayContact() const;

  };                         

  

// Maximum number of contacts

const int MAXCONTACTS = 10;


// Global Prototypes

void DisplayAllContacts(const Contact contacts[MAXCONTACTS],int count);


void main()  

  {

    Contact contacts[MAXCONTACTS];

    char answer;

    int count = 0;

    while( count < MAXCONTACTS )// while more room

      {

         // Ask the user if they want to continue

         cout << "Do you want to add a contact [Y]es/[N]o: ";

         cin >> answer;

         cin.ignore(80,'\n'); // skip rubbish

    

         if (answer == 'y' || answer == 'Y')

           {

             // Add the information

             contacts[count].AddContact();

             count++;

           }

         else

           break;

      }

    

    DisplayAllContacts(contacts,count);

    

  }                                         

//

// DisplayContact displays a single name

//

void Contact::DisplayContact() const 

  {

    cout << endl;

    cout << "Name    : " << name << endl;

    cout << "Age     : " << age << endl;

    cout << "phone no: " << phoneNo << endl;

    cout << endl;

  }

//

// DisplayAllContacts calls DisplayContact to show

// all entered names

//

void DisplayAllContacts(const Contact contacts[MAXCONTACTS],int count)

  {

    for (int i = 0; i < count; i++)

      {

        contacts[i].DisplayContact();

      }    

  } 

//

// Add contact asks for one contact

//

void Contact::AddContact()

  {

    cout << "Name: ";

    cin.getline(name,30);

    cout << "Phone no: ";

    cin.getline(phoneNo,15);

    cout << "Age ";

    cin >> age;

    cin.ignore();

  }

====================

// Filename: CONTINU2.CPP

// Use continue when data is missing

// and break when the user finishes early

#include <iostream.h>

void main()

{

  int count;       // Loop control variable

  float dSales;    // Will hold each day's sales

  float wSales=0;  // Weekly total


  // Set up the loop for a possible of five iterations

  for (count=0; count<5; count++)

    {

      cout << "Enter the sales for day #" << (count+1)

           << " (-99 for none): ";

      cin >> dSales;

      if (dSales < -98.9)  // User entered -99

        { continue; }

      if (dSales < 0.0)    // User entered -1

        { break; }


      // The following statement executes ONLY if a

      // valid daily sales total were just entered

      wSales += dSales;

    }


  // Print the week's total

  cout.precision(2);

  cout.setf(ios::showpoint);

  cout.setf(ios::fixed);

  cout << "The weekly total is $" << wSales ;

  return;

}

===========================

// Filename: CONTINUE.CPP

// Uses continue when data is missing

#include <iostream.h>


void main()

{

  int count;          // Loop control variable

  float dSales;       // Will hold each day's sales

  float wSales = 0;   // Weekly total


  // Set up the loop for a possible five iterations

  for (count = 0; count < 5; count++)

    {

      cout << "Enter the sales for day #" << (count + 1)

           << " (-99 for none): ";

      cin >> dSales;

      if (dSales < 0.0)

        { continue; }


      // The following statement executes ONLY if a

      // valid daily sales total was just entered

      wSales += dSales;

    }


  // Print the week's total

  cout.precision(2);

  cout.setf(ios::showpoint);

  cout.setf(ios::fixed);

  cout << endl << "The weekly total is $" 

       << wSales << endl;

  return;

}

==========================

// Filename: COUNTRY.CPP

// Allocates ten country names on the heap.

#include <iostream.h>

#include <string.h>


void allMem(char * countries[10]);

void initMem(char * countries[10]);

void prMem(char * countries[10]);

void freeMem(char * countries[10]);


void main()

{

  char * countries[10];  // Pointers to each country name

  allMem(countries);     // Allocate the memory

  initMem(countries);    // Store the country names

  prMem(countries);      // Print the country names

  freeMem(countries);    // Deallocate the memory


  return;

}

//**********************************************************

void allMem(char * countries[10])

{

  int ctr;

  for (ctr=0; ctr<10; ctr++)

  { countries[ctr] = new char [15]; }

  return;

}

//**********************************************************

void initMem(char * countries[10])

{

  strcpy(countries[0], "Italy");

  strcpy(countries[1], "Canada");

  strcpy(countries[2], "New Zealand");

  strcpy(countries[3], "France");

  strcpy(countries[4], "Chile");

  strcpy(countries[5], "Japan");

  strcpy(countries[6], "Brazil");

  strcpy(countries[7], "Mexico");

  strcpy(countries[8], "Greece");

  strcpy(countries[9], "Egypt");

  return;

}

//**********************************************************

void prMem(char * countries[10])

{

  int ctr;

  cout << "Here are the countries stored on the heap:" << endl;

  for (ctr=9; ctr>=0; ctr--)

  { cout << countries[ctr] << endl; }

  return;

}

//**********************************************************

void freeMem(char * countries[10])

{

  int ctr;

  for (ctr=0; ctr<10; ctr++)

  { delete countries[ctr]; }

  return;

}

===========================================

/* Filename: CPPADV.CPP */

// Shows some advantages and shortcuts of C++

#include <iostream.h>

#include <string.h>


struct People {

  char * name;     // Will allocate each name

  int weight;

};


void getData(People dieter[4]);

void calcData(float & weight);

void prData(People dieter[4]);

void dealData(People dieter[4]);


main()

{


  cout << "** Calculating a diet's weight loss **" << endl << endl << endl;

  cout << "I'll ask for four people's names and";

  cout << " weights and" << endl << "then calculate their expected";

  cout << " weight loss after two weeks." << endl << endl;


  // Define the four structure variables in the middle

  // C++ programmers often use uppercase letters for structures

  People dieter[4];


  // Pass the variables to a function

  // to allocate each name and fill the variables

  getData(dieter);


  // Pass the weights, by reference, to a calculate function

  for (int ctr=0; ctr<4; ctr++) // Don't redefine control variable

    {  // Pass just the weight of each array variable

       // Due to a structure-passing conversion, save

       // the structure's weight in a stand-alone variable

       // before passing it. You cannot pass the middle of

       // a structure by reference.

       float passWeight = dieter[ctr].weight;

       calcData(passWeight);

       calcData(passWeight);

       dieter[ctr].weight = passWeight;  }

  // Pass the variables to a print function

  prData(dieter);


  // Pass the variables to deallocate names

  dealData(dieter);


  return 0;

}

//**********************************************************

void getData(People dieter[4])

{

  char buffer[80];   // For temporary input

  for (int ctr=0; ctr<4; ctr++)

    { cout << "What is dieter #" << (ctr+1) << "'s name? ";

      cin >> buffer;

      // Make name pointer in each variable point to heap

      dieter[ctr].name = new char[strlen(buffer)+1];

      strcpy(dieter[ctr].name, buffer);

      cout << "What is dieter #" << (ctr+1) << "'s weight? ";

      cin >> dieter[ctr].weight;

    }

  return;

}

//**********************************************************

void calcData(float & weight)

{

  weight *= .85;

  return;

}

//**********************************************************

void prData(People dieter[4])

{

  cout << endl << "Here are the predicted results after 3 weeks:";

  for (int ctr=0; ctr<4; ctr++)

  {

    cout << "" << endl << dieter[ctr].name << " will weigh "

         << dieter[ctr].weight;

  }

  return;

}

//**********************************************************

void dealData(People dieter[4])

{

  for (int ctr=0; ctr<4; ctr++)

    { delete dieter[ctr].name; }

  return;

}

======================================

// Filename: CRREAD.CPP

// Creates a file then reads it


#include <fstream.h>



void main()

{

  fstream myFile;   // Inputs file pointer

  char inChar;


  myFile.open("c:\\data.txt", ios::out | ios::in);

  if (!myFile)

  {

    cout << endl << "*** Error opening file ***" << endl;

    return;

  }

  myFile << "Line 1 in DATA.TXT" << endl;

  myFile << "Line 2 in DATA.TXT" << endl;

  myFile << "Line 3 in DATA.TXT" << endl;

  myFile << "Line 4 in DATA.TXT" << endl;


  myFile.seekg(0L, ios::beg);

  cout << "The file:" << endl;

  while (myFile.get(inChar))

    { cout << inChar; }   // Outputs characters to the screen



  myFile.close();

  return;

}