Lecture 6 Examples


image from book

Open table as spreadsheet

Program

Demonstrates

account.cpp

Demonstration of a C++ structure which illustrates a function as a member.

account2.cpp

Demonstration of a C++ structure whose definition is in the file: theAccount.h and whose member functions are in the file theAccount_h.cpp

theAccount.h

This file contains the definition of the structure circle. The functions for the structure are place in the source file: circle_H.cpp

theAccount_h.cpp

This file contains the member functions for the structure circle that are contained in the header file: circle.h. This file should be a source file in the project.

CLOCK1.CPP

Demonstration of a C++ structure which illustrates a function as a member

DATESTRC.CPP

This program seeks a date and tells what day of the week it is.

ed.cpp

Demonstrates that errors may occur in a program in which two enumerators of an enumerated data type have the same integral values.

ENUM1.CPP

A demonstration of enumerated data types

ENUM2.CPP

A program to test assignment the use of pointers with enumerators and instances of enumerated data types.

ENUM3.CPP

A program to test assignment of integers to an enumerated data type and to perform integral arithmetic on the enumerated instances.

ENUM4.CPP

A program to test whether enumerated data types can have enumerators using the same name.

ENUM5.CPP

A program to test whether enumerated data types can have be used for I/O.

ENUM6.CPP.

A program to test enumerated data type which are used at both input and output of a function.

invoices.cpp

This program processes invoices.

Design files for invoice.cpp

  • Sample data: inventory_test.txt

  • UML of the structure: inventory

  • UML of the structure: items

  • Structure chart: sc_invoice

  • Pseudo code: pc_invoices

These files are used for the Design Phase of the program: invoices.cpp.

invoices2.cpp

This is a modification of the program: invoices.cpp.

Design files for invoices2.cpp

Sample data: inventory_test.txt

UML of the structure: inventory

UML of the structure: items

Structure chart: sc_invoices2

Pseudo code: pc_invoices2

These files are used for the Design Phase of the program: invoices2.cpp.

PTRSTRC.CPP

Demonstration of a C++ structure with pointers to unnamed instances.

STRUCT1.CPP

Demonstration of structure's features in C++.

STRUCT2.CPP

This program illustrates a struct definition, struct variable definition, struct assignment, and the manipulation of struct members.

STRUC3.CPP

This program illustrates an anonymous structure

STRUCT4.CPP

This program illustrates an anonymous structure

STUDENTGRADES.CPP

This program demonstrates the use of arrays of instances of a structure.

STUDENTGRADES2.cpp

This program demonstrates the use of a separate header file that contains the definition of a structure. It needs quizzes.h

QUIZZES.H

This header file is to be included into the program studentgrades2.cpp. It contains the definition of the structure: Quiz.

theClock.cpp

Demonstrates a timer and how to keep data at the same place on the screen. It uses the system date and time to begin the clock.

thedate.h

Contains the definition of the class date that can be used in many different examples.

THE_DATE.CPP

The program has the date structure with member functions.

TYPEDEF1.CPP

A program to test whether typedef can have be used for I/O.

image from book

 //  program_id      account2.cpp //  author        Don Voils //  date_written   08/03/2006 // //  description        Demonstration of a C++ structure //            which illustrates a function as a member. //                                 It is similar to account.cpp except the //                                 structure: Account is stored in its own //                                 files. // // #include<iostream> #include<iomanip> using namespace std; #include "theAccount.h" void main() {     cout << fixed << setprecision(2);   Account myAccount;   float theAmount;   cout << "What was the balance of the account when it started? ";   cin >> theAmount;   myAccount.settheBalance(theAmount);   cout << "What is the amount of the deposit? ";   cin >> theAmount;   myAccount.doDeposit(theAmount);   cout << "What is the amount of the withdrawal? ";   cin >> theAmount;   myAccount.doWithdrawal(theAmount);   cout << "The current balance is $" << myAccount.gettheBalance();   cout << endl << endl;   char resp;   cout << endl << endl << "Continue? ";   cin >> resp;   cout << endl << endl; } //  program_id     account.cpp //  author       Don Voils //  date_written  08/03/2006 // //  description       Demonstration of a C++ structure //                  which illustrates a function as a member. // // #include<iostream> #include<iomanip> using namespace std; struct Account {    float theBalance;    void settheBalance(float);    float gettheBalance();    void doDeposit(float);    void doWithdrawal(float); }; void Account::settheBalance(float theAmount) {   theBalance = theAmount; } float Account::gettheBalance() {    return theBalance; } void Account::doDeposit(float theAmount) {    theBalance += theAmount; } void Account::doWithdrawal(float theAmount) {    theBalance -= theAmount; } void main() {    cout << fixed << setprecision(2);    Account myAccount;    float theAmount;    cout << "What was the balance of the account when it started? ";    cin >> theAmount;    myAccount.settheBalance(theAmount);    cout << "What is the amount of the deposit? ";    cin >> theAmount;    myAccount.doDeposit(theAmount);    cout << "What is the amount of the withdrawal? ";    cin >> theAmount;    myAccount.doWithdrawal(theAmount);    cout << "The current balance is $" << myAccount.gettheBalance();    cout << endl << endl;    char resp;    cout << endl << endl << "Continue? ";    cin >> resp;    cout << endl << endl; } //   program_id    clock1.cpp // //   author      Don Voils //   date_written 08/03/2006 // //   description                Demonstration of a C++ structure //             which illustrates a function as //             a member. // //  Note: putch() and kbhit() had to be changed to _putch and _kbhit() //         in Visual Studio .NET 2005 because of security reason. //   #include<iostream>   #include<conio.h>   using namespace std;   char backspace;   struct block   {      char spacer[2];   }spacer_zero={"0"},spacer_blank={""};   struct time   {      int   hours,            minutes,            seconds;      void start_clock();      void tick_clock();      void display_clock();   };   void time::start_clock()   {      char mark;      cout << "Example:     hh:mm:ss"<< endl << endl                 << "Use a 24 hour clock" << endl << endl                 << "What is the time in hours, minutes and seconds?";      cin >> hours >> mark >> minutes >> mark >> seconds;   }   void time::display_clock()   {      long   counter;      block  hours_zero,           minutes_zero,           seconds_zero;      if (hours<=9)           hours_zero=spacer_zero;      else           hours_zero=spacer_blank;      if (minutes<=9)           minutes_zero=spacer_zero;      else           minutes_zero=spacer_blank;      if (seconds<=9)            seconds_zero=spacer_zero;      else            seconds_zero=spacer_blank;      for (counter=1;counter<=8;++counter)           _putch(backspace);      for (counter=1;counter<=8;++counter)           _putch('');      for (counter=1;counter<=8;++counter)           _putch(backspace);      cout << hours_zero.spacer << hours << ':' << minutes_zero.spacer                 << minutes << ':' << seconds_zero.spacer << seconds;   }   void time::tick_clock()   {      ++seconds;      if (seconds >=60)      {            seconds -= 60;            ++minutes;      }      if (minutes >=60)      {           minutes -= 60;           ++hours;      }      if (hours >=24)      {           hours = 0;      }   }   void main()   {      unsigned long  counter;      time day1;      backspace = '\b';      for(counter=1;counter<=5000;++counter)           cout << endl;      cout << flush;      day1.start_clock();      for (counter=1;counter<=5000;++counter)            cout << endl;      cout << flush;      while(!_kbhit())      {          day1.tick_clock();          day1.display_clock();          for(counter=1;counter <= 450000000;++counter);      } } // program_id     datestrc.cpp // author       Don Voils // date_written  08/03/2006 // // program description This program seeks a //            date and tells what day //            of the week it is. // // Formula must be adjusted for dates before 11/24/34. // #include<iostream> #include<string> using namespace std; // USER DEFINED DATA TYPES // typedef int COUNTER; struct date {    long    month,          day,          year;    void set_date();    void find_day_of_week_for(); }; // FUNCTIONAL PROTOTYPES // long days_between(date a_date); long days_since(date a_date); long f(date a_date); long g(date a_date); void clear_screen(); bool incorrect_date(date a_date); long days_in_month(date a_date); bool is_leap_year(date a_date); void main() {    date today_s_date;    clear_screen();    today_s_date.set_date();    today_s_date.find_day_of_week_for();    char resp;    cout << endl << endl << "Continue? ";    cin >> resp;    cout << endl << endl << endl; } void date::set_date() {    date a_date;    char dash;    int theCount = 0;    do    {        a_date.month = 0L;        a_date.day = 0L;        a_date.year = 0L;        if(theCount==0)        cout << endl << endl << "FINDING THE DAY OF THE WEEK"                << endl << endl;        else             cout << endl << endl <<"Error in entering date. Please try again. "                << endl << endl;      month = 0L;      day = 0L;      year = 0L;      cout << "What is the date? MM/DD/YY ";      cin >> month >> dash >> day >> dash >> year;      if(year<10)         year = year + 2000L;      else         if(year < 100)            year = year + 1900L;      a_date.month = month;      a_date.day = day;      a_date.year = year;      ++theCount;   }while(incorrect_date(a_date)); } void date::find_day_of_week_for() {      date a_date;      int number;      a_date.month=month;      a_date.day=day;      a_date.year=year;   string day_name[7]= {"Saturday", "Sunday", "Monday", "Tuesday",                "Wednesday", "Thursday", "Friday"};      string month_name[13]={"","January", "February", "March", "April",                    "May", "June", "July", "August",                    "September", "October", "November", "December"};   number = (int)(days_between(a_date) % 7L);   cout << endl << endl << month_name[month] << " " << day << ", "      << year << " was a " << day_name[number] << endl << endl; } long days_between(date day) {    date t_date;    t_date.month=11L;    t_date.day=24L;    t_date.year=1934L;    long number = days_since(day) - days_since(t_date);    return(number); } long days_since(date a_date) {    long number = 1461L*f(a_date)/4L + 153L*g(a_date)/5L + a_date.day;    return(number); } long f(date a_date) {    long number = (a_date.month<=2L) ? a_date.year - 1L : a_date.year;    return(number); } long g(date a_date) {    long number = (a_date.month<=2L) ? a_date.month + 13L :                    a_date.month + 1L;    return(number); } void clear_screen() {    for(COUNTER index=1;index<=25;++index)       cout << endl; } bool incorrect_date(date a_date) {   bool bad_date;   if (((a_date.month>=1L) && (a_date.month<=12L)) &&       ((a_date.day>=1L) && (a_date.day<=days_in_month(a_date))))       bad_date = false;   else       bad_date = true;   return(bad_date); } long days_in_month(date a_date) {    int upper_limit;    long days_in_month[] = {0L, 31L, 28L, 31L, 30L, 31L, 30L,                   31L, 31L, 30L, 31L,30L, 31L};       if (a_date.month != 2L)         upper_limit = days_in_month[a_date.month];    else       if (is_leap_year(a_date))           upper_limit = 29L;       else          upper_limit = days_in_month[a_date.month];    return (upper_limit); } bool is_leap_year(date a_date) {   bool a_leap_year;   if (((a_date.year%4L == 0L) && (a_date.year%100L != 0L))       || (a_date.year%400L == 0L))       a_leap_year = true;   else      a_leap_year = false;   return(a_leap_year); } // program_id      ed.cpp // written_by      don voils // date_written    8/12/2006 // description     This program demonstrates that errors may //                  occur in a program in which two enumerators //                  of an enumerated data type have the same //                  integral values. // #include<iostream> using namespace std; enum colors {green, blue, red, orange=2}; void main() {   colors ed,          don;     ed = red;     don = orange;     if(ed == orange)           cout << "ed is orange." << endl;     else           cout << "ed is red." << endl;     if(don == red)          cout << "don is red." << endl;     else          cout << "don is orange." << endl;     for(colors index = green; index < orange; index =          static_cast<colors>(static_cast<int>(index) + 1))     {          switch(index)          {               case green:                    cout << "index is green."<< endl << endl;               case blue:                    cout << "index is blue."<< endl << endl;     //   Notice this line is commented           //            out because there would be two           //            cases with the same value:           //                         case red:     //             cout << "index is red."<< endl << endl;               case orange:                    cout << "index is orange." << endl << endl;               default:                    cout << "index is not a color. " << endl << endl;          }     } } //   program_id         enum1.cpp // //   author           don voils //   date_written       08/31/2006 // //   program descriptsion   A demonstration of enumerated data types // #include<iostream> using namespace std; enum Boolean {FALSE, TRUE}; void main(void) {      float score;      Boolean scoreFlag;      for(short index = 1;index <= 25; ++index)           cout << endl;      cout << "What was the score? ";      cin >> score;      if (score>100)         scoreFlag = TRUE;      else         scoreFlag = FALSE;             if (scoreFlag)           cout << endl << endl << "The goal has been met.";      else           cout << endl << endl << "The goal has not been met.";      cout << endl << endl;      char resp;      cout << endl << endl << "Continue? ";      cin >> resp;      cout << endl << endl; } //   program_id       enum2.cpp //   author         don voils //   date_written     08/31/2006 // //   program description    A program to test assignment //                                 the use of pointers with //            enumerators and instances of //                  enumerated data types. // #include<iostream> using namespace std; enum Suit {CLUB, SPADE, HEART, DIAMOND}; void main() {      Suit card1Type;      Suit *cardPointer;      card1Type = SPADE;   // The following line will cause an error.   //   // cardPointer = &SPADE;      cardPointer = &card1Type;      cout << "The card is a " << card1Type << " and is at location "           << cardPointer << endl << endl << endl;      char resp;      cout << endl << endl << "Continue? ";      cin >> resp;      cout << endl << endl; } //   program_id         enum3.cpp //   author           don voils //   date_written       08/31/2006 // //   program description    A program to test assignment //            of integers to an enumerated //            data type and to perform //            integral arithmetic on the //            enumerated instances. // #include<iostream> using namespace std; enum Colors {BLUE, RED, YELLOW, GREEN}; void main(void) {      Colors carColor, truckColor = BLUE;      // Notice that if you remove any of the following comments      // the program will not compile. Arithmetic with enumerators      // is no longer allowed.      //   // carColor = 3;   // cout << endl << "The car's color is " << carColor;   //       carColor = truckColor + RED;   // cout << endl << "The car's color is " << carColor;   // carColor = truckColor + 1;   // cout << endl << "The car's color is " << carColor;   // carColor = truckColor - 2;   //       cout << endl << "The car's color is " << carColor;     char resp;     cout << endl << endl << "Continue? ";     cin >> resp;     cout << endl << endl; } //   program_id         enum4.cpp //   author           don voils //   date_written       08/31/2006 // //   program description    A program to test whether enumerated data //                               types can have enumerators using the same //                               name. // #include<iostream> using namespace std;    // This program should not compile because the names used as    // enumerators below are the same in two different enumerated data types.    // enum Color {BLUE, RED, YELLOW, GREEN}; enum Shades {BLUE, RED, YELLOW, GREEN}; enum Style {TRUCK, COUPS, FOURDOOR, WAGON}; void main(void) {      Shades carColor;      Shades truckColor = BLUE;      Style vehicle;      carColor = truckColor;      cout << "The car color is " << carColor << endl;      vehicle = truckColor;      cout << "The vehicle shade is " << vehicle << endl;            char resp;            cout << endl << endl << "Continue? ";            cin >> resp;            cout << endl << endl; } //   program_id         enum5.cpp // //   author           don voils //   date_written       08/31/2006 // //   program description   A program to test whether enumerated data //                              types can have be used for I/O. // #include<iostream> using namespace std; enum {BLUE, RED, YELLOW, GREEN}; enum Boolean {FALSE, TRUE}; void main() {      int vehicle = RED;      Boolean closeQuarter = TRUE;      cout << "The vehicle shade is " << vehicle << endl; // // The following code will not compile. //      cout << "Should we close the quarter? (0=NO, 1=YES) "; //   cin >> closeQuarter;      if (closeQuarter)            cout << endl << "Closing quarter!";      else            cout << endl << "Not closing quarter now!";             char resp;             cout << endl << endl << "Continue? ";             cin >> resp;             cout << endl << endl; } //   program_id         enum6.cpp //   author           don voils //   date_written       10/16/2006 // //   program description   A program to test enumerated //            data type which are used at //                                both input and output of a function. // #include<iostream> using namespace std; enum Colors {BLACK=1, RED, YELLOW, GREEN, BLUE}; Colors basicColor(Colors theCar); void main() {    Colors myCar;    for(myCar = BLACK ;myCar <= BLUE;           myCar = static_cast<Colors> (static_cast<int>(myCar) + 1))    {         basicColor(myCar);    }    cout << "My car is no longer one of the basic colors." << endl;    cout << endl << endl;    char resp;    cout << endl << endl << "Continue? ";    cin >> resp;    cout << endl << endl; } Colors basicColor(Colors theCar) {    switch(theCar)    {      case 1:        cout << "My car is black." << endl;        break;      case 2:        cout << "My car is red." << endl;        break;      case 3:        cout << "My car is yellow." << endl;        break;      case 4:        cout << "My car is green." << endl;        break;      case 5:        cout << "My car is blue." << endl;        break;      default:        cout << "My car is not one of the basic colors." << endl;        break;    }    return theCar; } 1212 Thing1 12.54 1531 Thing2 54.23 4532 Thing3 242.45 5432 Thing4 51.33 //   program_id     inventory //   written_by     don voils //   date_written   3/2/2006 //   description    This file contains the UML for the structure: inventory. // // 

image from book

 // program-id    invoices2.cpp // written-by    don voils // date-written  1/21/2006 // // description   This program is a modification of the program: invoices.cpp //               This program is menu driven and adds the features that //               permits the user to add and delete items from the inventory //               as well as saving the inventory to disk with it ends. // #include<iostream> #include<fstream> #include<iomanip> #include<string> using namespace std; // This structure will store data from the // file inventoryText.txt and any changes during // the program execution. // struct inventory {      long itemNumber;      string itemName;      double unitPrice; }; // This structure will store data about the // customer invoices. // struct items {      inventory itemOrdered;      int numberOrdered; }; // The function prototypes // void loadInventory(inventory inventoryItems[],short &inventoryNumber); void saveInventory(inventory inventoryItems[],short inventoryNumber); void addInventory(inventory inventoryItems[],short &inventoryNumber); void deleteInventory(inventory inventoryItems[],short inventoryNumber); void processCustomer(inventory inventoryItems[],short &inventoryNumber); void loadInvoice(inventory inventoryItems[],short &inventoryNumber,                  items invoiceItems[],short &numberItems); void showInvoice(string customerName,string customerAddress,                 items invoiceItems[],short numberItems); void displayTableHeading(string customerName,string customerAddress); void displayInvoice(items invoiceItems[],short numberItems); void clearScreen(); void main() {   char resp;   short menuItem;   short inventoryNumber = 0;   bool continueProgram = true;   inventory inventoryItems[200];   loadInventory(inventoryItems,inventoryNumber);   do   {     clearScreen();     cout << "         Menu" << endl << endl;     cout << "    1. Add Inventory Items" << endl;     cout << "    2. Delete Inventory Items" << endl;     cout << "    3. Enter and Display Customer Invoice" << endl;     cout << "    4. End Program" << endl << endl;     cout << endl << "Which option? ";     cin >>menuItem;     switch(menuItem)     {      case 1:           clearScreen();           addInventory(inventoryItems,inventoryNumber);           break;      case 2:     clearScreen();           deleteInventory(inventoryItems,inventoryNumber);           break;      case 3:     clearScreen();           processCustomer(inventoryItems,inventoryNumber);           break;      case 4:     clearScreen();           saveInventory(inventoryItems,inventoryNumber);           continueProgram = false;           break;           default: cout << "Wrong menu option" << endl;           cout << "Continue? (y/n)";           cin.get(resp).get();     }   }while(continueProgram); } // This function stores the data contained in the file inventoryText.txt // into the array theInventory[] // void loadInventory(inventory inventoryItems[],short &inventoryNumber) {   ifstream inFile("inventory.txt");   if(!inFile)   {      cout << endl << "The file did not open";      exit(1);   }   inFile >> inventoryItems[inventoryNumber].itemNumber;   while(inFile)   {     inFile >> inventoryItems[inventoryNumber].itemName;     inFile >> inventoryItems[inventoryNumber].unitPrice;     ++inventoryNumber;     inFile >> inventoryItems[inventoryNumber].itemNumber;   } } void saveInventory(inventory inventoryItems[],short inventoryNumber) {   ofstream outFile("inventory.txt");   if(!outFile)   {     cout << endl << "The file did not open";     exit(1);   }   for(int index = 0;index < inventoryNumber;++index)      if(inventoryItems[index].itemNumber!=0)      {           outFile << inventoryItems[index].itemNumber << endl;                        outFile << inventoryItems[index].itemName << endl;                        outFile << inventoryItems[index].unitPrice << endl;      } } // This function permits the entry of addtional inventory // items into the array inventoryItems[]. // void addInventory(inventory inventoryItems[],short &inventoryNumber) {      char resp;      bool notThere = true;      long itemNumber;      clearScreen();      if(inventoryNumber < 200)      {                  cout << endl << "What is the item number of the item being added? ";           cin >> itemNumber;           if(itemNumber<1000)           {                 cout << endl << "That is not an acceptable item number." << endl;                 notThere = false;                 cout << endl << "Continue? (y/n)";                 cin.get(resp).get(resp);           }           for(int index = 0; index < inventoryNumber;++index)           {             if(itemNumber==inventoryItems[index].itemNumber)             {                               cout << endl << "That inventory item number is already on record."                                    << endl;                    cout << endl << "Continue? (y/n)";                    cin.get(resp).get(resp);                    notThere = false;             }           }           if(notThere)           {               cin.get();               inventoryItems[inventoryNumber].itemNumber = itemNumber;               cout << endl << "What is the item name? ";                     getline(cin,inventoryItems[inventoryNumber].itemName);               cout << endl << "What is the unit price? ";               cin >> inventoryItems[inventoryNumber].unitPrice;               ++inventoryNumber;           }      }      else      {        cout << endl << "There is no more room to add to the inventory."                   << endl;        cout << endl << "Continue? (y/n)";        cin.get(resp).get();      } } // This function permits the user to delete inventory items // from the array inventoryItems[]. // void deleteInventory(inventory inventoryItems[],short inventoryNumber) {      char resp;      bool notThere = true;      long itemNumber;      cout << endl << "What is the item number of the item being deleted? ";      cin >> itemNumber;      if(itemNumber<1000)      {            cout << endl << "That is not an acceptable item number." << endl;            notThere = false;            cout << endl << "Continue? y/n)";            cin >> resp;      }      for(int index = 0; index < inventoryNumber;++index)      {           if(itemNumber==inventoryItems[index].itemNumber)           {              inventoryItems[index].itemNumber = 0;                           cout << endl << "That inventory item number is being deleted."                                << endl;                     cout << endl << "Continue? (y/n)";              cin >> resp;              notThere = false;            }      }      if(notThere)      {            cout << endl << "There was no such item in the inventory." << endl;            cout << endl << "Continue? y/n)";            cin >> resp;      } } // The function processes the entry and displaying of // customer information and data about the items // purchased and then permits the invoice to be displayed // on the screen. // void processCustomer(inventory inventoryItems[],short &inventoryNumber) {   string resp;   short numberItems = 0;   string customerName;   string customerAddress;   items invoiceItems[10];   clearScreen();   cin.get();   cout << "What is the customer's name? ";   getline(cin,customerName);   cout << endl << "What is the customer's address? ";   getline(cin,customerAddress);   cout << endl;   cout << endl;   loadInvoice(inventoryItems,inventoryNumber,invoiceItems,numberItems);   showInvoice(customerName,customerAddress,invoiceItems,numberItems);   cout << endl << "Continue? ";   cin >> resp; } void showInvoice(string customerName,string customerAddress,                 items invoiceItems[],short numberItems) {   clearScreen();   displayTableHeading(customerName,customerAddress);   displayInvoice(invoiceItems,numberItems); } // This function permit the entry of items purchased by // a user. // void loadInvoice(inventory inventoryItems[],short &inventoryNumber,                  items invoiceItems[],short &numberItems) {   clearScreen();   char resp;   long itemNumber;   long deletedItem = 0;   short number;   bool itemNotThere;   for(short index=0;index < 10;++index)   {     do     {        cout << endl << "What is the item's number? ";        cin >> itemNumber;        itemNotThere = true;        if(deletedItem == itemNumber)           cout << "That item is not in the inventory"                            << endl << endl;        else        {           for(short counter = 0; counter < inventoryNumber;                                     ++counter)           {                             if(inventoryItems[counter].itemNumber==itemNumber)              {                 cout << endl                                    << "How many of those items do you want? ";                cin >> number;                invoiceItems[numberItems].itemOrdered.itemNumber =                                 inventoryItems[counter].itemNumber;                invoiceItems[numberItems].itemOrdered.itemName =                                 inventoryItems[counter].itemName;                invoiceItems[numberItems].itemOrdered.unitPrice =                                 inventoryItems[counter].unitPrice;                invoiceItems[numberItems].numberOrdered = number;                ++numberItems;                itemNotThere = false;                clearScreen();              }           }        }        if(itemNotThere)         cout << endl << "That item is not in the inventory" << endl;        if(numberItems < 10)        {           cout << endl << "Do you want to enter another item?";           cin >> resp;           if(resp=='N' || resp=='n')                 break;           clearScreen();        }     }while(resp!='n' && resp!= 'N');     if(resp=='N' || resp=='n')           break;   } } // This function displays the heading of the customer invoice. // void displayTableHeading(string customerName,string customerAddress) {   cout << left << setw(12) << "Name: " << customerName << endl;   cout << left << setw(12) << "Address: " << customerAddress        << endl << endl;   cout << left << setw(12) << "Item Number"        << left << setw(12) << "Item Name"        << left << setw(15) << "Unit Price"        << left << setw(12) << "# Ordered"        << left << setw(12) << "Item Amount" << endl; } // This function displays the body of the customer invoice. // void displayInvoice(items invoiceItems[],short numberItems) {   double totalInvoice = 0.00;   double amount;   for(short index = 0; index < numberItems; ++index)   {     cout << fixed << setprecision(2);     amount = invoiceItems[index].itemOrdered.unitPrice *                        invoiceItems[index].numberOrdered;     cout << left << setw(12) << invoiceItems[index].itemOrdered.itemNumber          << left << setw(12) << invoiceItems[index].itemOrdered.itemName          << right << "$"                 << setw(12) << invoiceItems[index].itemOrdered.unitPrice                 << right << setw(12) << invoiceItems[index].numberOrdered          << " $" << setw(12)<< amount << endl;     totalInvoice += amount;   }   cout << endl << right << setw(38) << "Invoice total $ "        << right << setw(25) << totalInvoice; } // This function clears the screen. // void clearScreen() {   for(short index = 0; index < 50; ++index)     cout << endl; } // program-id     invoices.cpp // written-by    don voils // date-written  8/23/2006 // // description   This program processes invoices // #include<iostream> #include<fstream> #include<iomanip> #include<string> using namespace std; // This data type stores inventory items. // struct inventory {      long itemNumber;      string itemName;      double unitPrice; }; // This data type store invoice items. // struct items {      inventory itemOrdered;      int numberOrdered; }; // These are the function prototypes. // void loadInventory(inventory inventoryItems[],short &inventoryNumber); void loadInvoice(inventory inventoryItems[],short &inventoryNumber,                  items invoiceItems[],short &numberItems); void displayTableHeading(string customerName,string customerAddress); void displayInvoice(items invoiceItems[],short numberItems); void clearScreen(); void main() {   char resp;   short inventoryNumber = 0;   inventory inventoryItems[200];   loadInventory(inventoryItems,inventoryNumber);   string customerName;   string customerAddress;   items invoiceItems[10];   do   {     cout << "What is the customer's name? ";     getline(cin,customerName) ;            cout << endl << "What is the customer's address? ";     getline(cin,customerAddress);            short numberItems = 0;     cout << endl;     loadInvoice(inventoryItems,inventoryNumber,invoiceItems,numberItems);     clearScreen();            displayTableHeading(customerName,customerAddress);     displayInvoice(invoiceItems,numberItems);     cout << endl << endl << "Process another customer? ";     cin.get(resp).get(resp).get();     clearScreen();   }while(resp=='Y' || resp=='y');   cout << endl << endl; } // This function loads the inventory from the disk. // void loadInventory(inventory theInventory[],short &inventoryNumber) {   ifstream inFile("inventory.txt");   if(!inFile)   {      cout << "The file did not open";      exit(1);   }   inFile >> theInventory[inventoryNumber].itemNumber;   while(inFile)   {            inFile >> theInventory[inventoryNumber].itemName;            inFile >> theInventory[inventoryNumber].unitPrice;     ++inventoryNumber;     inFile >> theInventory[inventoryNumber].itemNumber;   } } // This function loads invoice data for a specific customer. // void loadInvoice(inventory inventoryItems[],short &inventoryNumber,                  items invoiceItems[],short &numberItems) {      clearScreen();      char resp;      long itemNumber;      //short numberOrdered = 0;      long deletedItem = 0;      short number;      bool itemNotThere;      for(short index=0;index < 10;++index)      {        do        {              cout << endl << "What is the item's number? ";              cin >> itemNumber;                     itemNotThere = true;              if(deletedItem == itemNumber)                 cout << "That item is not in the inventory" << endl << endl;              else              {                for(short counter = 0; counter < inventoryNumber; ++counter)                {                                 if(inventoryItems[counter].itemNumber==itemNumber)                   {                       cout << endl << "How many of those items do you want? ";                       cin >> number;                       invoiceItems[numberItems].itemOrdered.itemNumber =                                                          inventoryItems[counter].itemNumber;                           invoiceItems[numberItems].itemOrdered.itemName =                                                          inventoryItems[counter].itemName;                       invoiceItems[numberItems].itemOrdered.unitPrice =                                                          inventoryItems[counter].unitPrice;                       invoiceItems[numberItems].numberOrdered = number;                       ++numberItems;                       itemNotThere = false;                                   clearScreen();                   }                }              }                           if(itemNotThere)                 cout << endl << "That item is not in the inventory" << endl;              if(numberItems < 10)              {                 cout << endl << "Do you want to enter another item?";                 cin >> resp;                 if(resp=='N' || resp=='n')                       break;                 clearScreen();              }        }while(resp!='n' && resp!= 'N');        if(resp=='N' || resp=='n')           break;      } } // This function displays the table heading to display the // invoices for the customer. // void displayTableHeading(string customerName,string customerAddress) {      cout << left << setw(12) << "Name: " << customerName << endl;      cout << left << setw(12) << "Address: " << customerAddress                   << endl << endl;              cout << left << setw(12) << "Item Number"                   << left << setw(12) << "Item Name"                   << left << setw(15) << "Unit Price"                   << left << setw(12) << "# Ordered"                   << left << setw(12) << "Item Amount" << endl; } // This function display the table body for the invoice // being displayed. // void displayInvoice(items theInvoice[],short numberOrdered) {      double totalInvoice = 0.00;      double amount;      for(short index = 0; index < numberOrdered; ++index)      {           cout << fixed << setprecision(2);           amount = theInvoice[index].itemOrdered.unitPrice *                       theInvoice[index].numberOrdered;           cout << left << setw(12) << theInvoice[index].itemOrdered.itemNumber                << left << setw(12) << theInvoice[index].itemOrdered.itemName                << right << "$"                             << setw(12) << theInvoice[index].itemOrdered.unitPrice                             << right << setw(12) << theInvoice[index].numberOrdered                << " $" << setw(12)<< amount << endl;           totalInvoice += amount;      }      cout << endl << right << setw(38) << "Invoice total $ "                 << right << setw(25) << totalInvoice; } // This function clears the screen. // void clearScreen() {   for(short index = 0; index < 50; ++index)     cout << endl; } //   program_id:     items //   written_by:     don voils //   date_written:   3/2/2006 //   description:    This file contains the UML for the structure: items. // // 

image from book

 //   program_id      pc_invoices2 //   written_by      don voils //   date_written   3/2/2006 // //   Description    This file contains the pseudo code for //                  the program: invoices2.cpp // Invoices2   Set inventoryNumber = 0   Process loadInventory(inventoryItems[],&inventoryNumber)   DO    Set continueProgram to True    Display menu options:       1. Add Inventory Items       2. Delete Inventory Items       3. Process Invoice       4. End Program        Which option?    Receive resp    CASE OF resp     '1': Process addInventory(inventoryItems[],&inventoryNumber)     '2': Process deleteInventory(inventoryItems[],inventoryNumber)     '3': Process processCustomers(inventoryItems[],&inventoryNumber)     '4': Process saveInventory(inventoryItems[],inventoryNumber)        Set continueProgram to False    END CASE   WHILE(continueProgram = True) End loadInventory(inventoryItems[],&inventoryNumber)   Open inventoryFile   Read inventoryFile and Store in inventoryItems[inventoryNumber].itemNumber   DOWHILE(invoiceFile not empty and inventoryNumber < maximumInventoryItems)     Read inventoryFile and Store in inventoryItems[inventoryNumber].itemName     Read inventoryFile and Store in inventoryItems[inventoryNumber].unitPrice     Set inventoryNumber = inventoryNumber + 1     Read inventoryFile and Store in inventoryItems[inventoryNumber].itemNumber   ENDDO Return saveInventory(inventoryItems[],inventoryNumber)   Open inventory.txt   FOR index FROM 0 TO inventoryNumber - 1     IF inventoryItems[index].itemNumber NOT EQUAL TO 0       SAVE inventoryItems[index].itemNumber TO inventoryFile       SAVE inventoryItems[index].itemName TO inventoryFile       SAVE inventoryItems[index].unitPrice TO inventoryFile     ENDIF   ENDFOR Return addInventory(inventoryItems[],&inventoryNumber)   Set notThere to True   IF inventoryNumber < 200 THEN     Request and Receive itemNumber     IF(itemNumber < 1000) THEN       Display error message       Set notThere to False     ENDIF     FOR index FROM 0 TO inventoryNumber - 1       IF itemNumber = inventoryItems[index].itemNumber THEN          Display error message          Set notThere to false       ENDIF     ENDFOR     IF notThere is True        Store itemNumber to inventoryItems[inventoryNumber].itemNumber        Request and Receive itemName        Store itemName to inventoryItems[inventoryNumber].itemName        Request and Receive unitPrice        Store unitPrice to inventoryItems[inventoryNumber].unitPrice        Set inventoryNumber = inventoryNumber + 1     ENDIF   ELSE     DISPLAY the inventory has no more room in it.   ENDIF Return deleteInventory(inventoryItems[],inventoryNumber)   Set notThere to True   Request and Receive itemNumber to Delete   IF itemNumber < 1000 THEN      Display error message      Set notThere to false   ENDIF   FOR index FROM 0 TO inventoryNumber - 1     IF itemNumber = inventoryItems[index].itemNumber THEN        Set inventoryItems[index].itemNumber to 0        Display confirmation message     ENDIF   ENDFOR   IF notThere = True THEN      Display Error message that the item number was not in the inventory.   ENDIF Return processCustomers(inventoryItems[],&inventoryNumber)   Request and Receive customerName and customerAddress   Set numberItems = 0   Process loadInvoice(inventoryItems[],&inventoryNumber,              invoiceItems[],&numberItems)   Process displayInvoice(inventoryItems[],inventoryNumber,              invoiceItems[],numberItems) Return loadInvoice(inventoryItems[],&inventoryNumber,invoiceItems[],&numberItems)   Set deletedItem = 0   FOR index FROM 0 TO 9     DO       Request and Receive itemNumber       Set itemNotThere to True       IF deleteItem = itemNumber THEN          Display error message       ELSE         FOR counter FROM 0 to inventoryNumber           IF(itemNumber = inventoryItems[index].itemNumber)THEN             invoiceItems[numberItems].itemOrdered.itemNumber =                        inventoryItems[index].itenNumber             invoiceItems[numberItems].itemOrdered.itemName =                        inventoryItems[index].itemName             invoiceItems[numberItems].itemOrdered.unitprice =                        inventoryItems[index].unitPrice             Request and Receive invoiceItems[numberItems].numberOrdered             Set numberItems = numberItems + 1             Set notThere = false;           ENDIF         ENDFOR       ENDIF       IF notThere = true THEN          Display error message       ENDIF       IF numberItems < 10 THEN          Request and Receive whether anotherItem       ENDIF     ENDWHILE(anotherItem is true)     IF anotherItem is false THEN        Leave module     ENDIF   ENDFOR Return displayInvoice(inventoryItems[],inventoryNumber,              invoiceItems[],numberItems)   Process displayTableHeading(customerName,customerAddress)   Process displayInvoice(invoiceItems[],numberItems) Return displayTableHeading(customerName,customerAddress)   Display customerName   Display customerAddress   Display in columns "Item Number", "Item Name", "Unit Price",                  "Number Ordered", "Item Total" Return showInvoice(invoiceItems[],numberItems)   Set invoiceTotal = 0.00   FOR index from 0 to numberItems - 1     Display in columns invoiceItems[index].itemOrdered.itemNumber,           invoiceItems[index].itemOrdered.itemName,           invoiceItems[index].itemOrdered.unitprice,           invoiceItems[index].numberOrdered           invoiceItems[index].numberOrdered * invoiceItems[].unitprice     Set invoiceTotal = invoiceTotal +           invoiceItems[index].numberOrdered * invoiceItems[index].unitprice   ENDFOR   Display in column invoiceTotal Return //   program_id    pc_invoices //   written_by    don voils //   date_written  3/2/2006 //   description   This file contains the pseudo code for the //                 program: invoices.cpp // Invoices   Set inventoryNumber = 0   Process loadInventory(inventoryItems[],inventoryNumber);   do     Request and Receive customerName and customerAddress     Set numberItems = 0     Process loadInvoice(inventoryItems[],inventoryNumber,               invoiceItems[],numberItems)     Process displayTableHeading(customerName,customerAddress)     Process displayInvoice(invoiceItems[],numberItems);     Request and Receive whether another invoice   while(another invoice) End loadInventory(inventoryItems[],&inventoryNumber)    Set maximumInventorItems = 200    Open inventoryFile    Read inventoryFile and Store in                     inventoryItems[inventoryNumber].itemNumber    DOWHILE(invoiceFile not empty and inventoryNumber < maximumInventoryItems)      Read inventoryFile and Store in                     inventoryItems[inventoryNumber].itemName      Read inventoryFile and Store in                     inventoryItems[inventoryNumber].unitPrice      Set inventoryNumber = inventoryNumber + 1      Read inventoryFile and Store in                     inventoryItems[inventoryNumber].itemNumber   ENDDO Return loadInvoice(inventoryItems[],&inventoryNumber,invoiceItems[],&numberItems)   Set maximumNumberItems = 10   do     Request and Receive itemNumber     Set notThere = true;     for index from 0 to inventoryNumber - 1       if(itemNumber = inventoryItems[index].itemNumber)then         invoiceItems[numberItems].itemOrdered.itemNumber =                        inventoryItems[index].itenNumber         invoiceItems[numberItems].itemOrdered.itemName =                        inventoryItems[index].itemName         invoiceItems[numberItems].itemOrdered.unitprice =                        inventoryItems[index].unitPrice         Request and Receive invoiceItems[numberItems].numberOrdered         Set notThere = false;       endif     endfor     if(notThere)then        Display error message     else        Set numberItems = numberItems + 1     endif     Request and Receive whether anotherItem   while(anotherItem and numberItems < maximumNumberItems Return displayTableHeading(customerName,customerAddress)   Display customerName   Display customerAddress   Display in columns "Item Number", "Item Name", "Unit Price",                  "Number Ordered", "Item Amount" Return displayInvoice(invoiceItems[],numberItems)   Set totalInvoice = 0.00   for index from 0 to numberItems - 1     Display in columns invoiceItems[index].itemOrdered.itemNumber,           invoiceItems[index].itemOrdered.itemName,           invoiceItems[index].itemOrdered.unitprice,           invoiceItems[index].numberOrdered           invoiceItems[index].numberOrdered *                         invoiceItems[].unitprice     Set totalInvoice = TotalInvoice +           invoiceItems[index].numberOrdered *                         invoiceItems[index].unitprice   endfor   Display in column totalInvoice Return // program_id    ptrstrc.cpp // author        Don Voils // date_written   06/03/2006 // // description   Demonstration of a C++ structure //               with pointers to unnamed instances. // #include<iostream> using namespace std; struct Date {    short theMonth,       theDay,       theYear; }; void main() {    Date theDate;    Date* ptr = &theDate;    theDate.theMonth = 7;    theDate.theDay = 4;    theDate.theYear = 1776;    cout << "The date is " << ptr -> theMonth << "/" << ptr -> theDay         << "/"<< ptr -> theYear << endl;    ptr -> theMonth = 8;    ptr -> theDay = 21;    ptr -> theYear = 1984;    cout << "The date is " << ptr -> theMonth << "/" << ptr -> theDay         << "/"<< ptr -> theYear << endl;    Date * ptr1 = new Date;    ptr1 -> theMonth = 7;    ptr1 -> theDay = 4;    ptr1 -> theYear = 2004;    cout << "The date is " << ptr1 -> theMonth << "/" << ptr1 -> theDay         << "/"<< ptr1 -> theYear << endl << endl << endl;    char resp;    cout << endl << endl << "Continue? ";    cin >> resp;    cout << endl << endl;    delete ptr1; } //   program_id    quizzes.h //   written_by    don voils //   date_written 3/2/2006 //   description   This file contain the definition of the //                 structure Quizzes. /* The following two lines prevent the possibility   of a redefinition of the structure Quizzes. */ #ifndef QUIZZES #define QUIZZES /* This header file is to be included   into the program studentgrades2.cpp */ struct Quizzes {    string firstName;    string lastName;    int quizGrades[5]; }; #endif //   program_id     sc_invoice2 //   written_by     don voils //   date_written   3/2/2006 //   description    This file contains the structure chart for the program: invoice2.cpp // 

image from book

 //   program_id     sc_invoice //   written_by     don voils //   date_written   3/2/2006 //   description    This file contains the structure chart for the program: invoice.cpp // 

image from book

 //   program_id     struct1.cpp //   author       don voils //   date written  08/31/2006 // //   program description   Demonstration of structure's //            features in C++. // #define AND && #define OR || #include<iostream> #include<iomanip> using namespace std; enum workType {salaried, hourly}; struct Date { int theMonth,     theDay,     theYear; }; struct Employee {      Date    hireDate;      workType    salaryType;      char    employeeLastName[15],               employeeFirstName[10];      float    unitPay; }; void main() {      char   dash;      Employee newStaff; //   Following two lines are not valid so must use next one //   try to remove the comments. // //   Employee oldStaff; //   oldStaff = { {6,12,70}, salaried, "Thomas", "John", 350.00};      Employee oldStaff = { {6,12,70}, salaried, "Thomas", "John", 350.00};      cout << "The name of the last employee was" << oldStaff.employeeLastName           << "," << oldStaff.employeeFirstName << "." << endl           << "Hired on " << oldStaff.hireDate.theMonth << "/"           << oldStaff.hireDate.theDay << "/"           << oldStaff.hireDate.theYear << "." << endl;      if (oldStaff.salaryType==salaried)            cout << "and was salaried at $" << setiosflags(ios::fixed)                 << setprecision(2) << setiosflags(ios::showpoint)                 << oldStaff.unitPay << endl;      else            cout << "and was hourly at $" << setiosflags(ios::fixed)                 << setprecision(2) << setiosflags(ios::showpoint)                 << oldStaff.unitPay << endl << endl;      cout << endl << endl << endl << "What is the new employee's name? ";      cin >> newStaff.employeeFirstName >> newStaff.employeeLastName;      cout << endl << endl << "What is the pay per unit of work? ";      cin >> newStaff.unitPay;      cout << endl << endl << "What was the hire date? ";      cin >> newStaff.hireDate.theMonth >> dash          >> newStaff.hireDate.theDay >> dash          >> newStaff.hireDate.theYear;      int salary;      cout << endl << endl << "Is the employee salaried (0) or hourly (1)? ";            cin >> salary;      newStaff.salaryType= static_cast<workType>(salary);      cout << endl << endl << "The name of the new employee is "                  << newStaff.employeeFirstName           << " " << newStaff.employeeLastName << "." << endl                  << "Hired on " << newStaff.hireDate.theMonth << "/"           << newStaff.hireDate.theDay << "/"           << newStaff.hireDate.theYear << "." << endl;      if (newStaff.salaryType==salaried)           cout << "and is salaried at $" << setiosflags(ios::fixed)                << setprecision(2) << setiosflags(ios::showpoint)                << newStaff.unitPay << endl;      else           cout << "and is hourly at $" << setiosflags(ios::fixed)                << setprecision(2) << setiosflags(ios::showpoint)                << newStaff.unitPay << endl;      cout << endl << endl; } // program_id          struc2.cpp // author         don voils // date written    08/31/2006 // // program description This program illustrates a struc //                      definition, struc variable definition, //                      struc assignment, and the manipulation //                      of struc members. // #include<iostream> using namespace std; struct Stuff {    char name[30];    float price; }; void main(void) {    Stuff item1 = {"Widget", 5.75};    Stuff item2;    item2 = item1;    cout << "The name of item 1 is " << item1.name << endl         << "The price of item 1 is " << item1.price << endl         << "The name of item 2 is " << item2.name << endl         << "The price of item 2 is " << item2.price << endl         << endl << endl; } // program_id       struct3.cpp // // author         don voils // date written    08/31/2006 // // program description This program illustrates using the dot operator //                     to access the data members of a structure //                     instance as well as showing that the size //                     of an instance is greater to or equal to the //                     sum of the sizes of the data members. // #include<iostream> using namespace std; struct Date {    int theMonth;    int theDay;    int theYear; }; void main() {    char dash;    Date invoiceDate;    cout << "What is the invoice date? ";    cin >> invoiceDate.theMonth >> dash >> invoiceDate.theDay        >> dash >> invoiceDate.theYear;    cout << endl << "Did you say that the invoice date is "         << invoiceDate.theMonth << "/" << invoiceDate.theDay         << "/" << invoiceDate.theYear << endl << endl << endl;    cout << endl << "The size of the month " << sizeof(invoiceDate.theMonth)         << endl << "The size of the day " << sizeof(invoiceDate.theDay)         << endl << "The size of the year " << sizeof(invoiceDate.theYear)         << endl << "The size of invoiceDate " << sizeof(invoiceDate) << endl;    char resp;   cout << endl << endl << "Continue? ";   cin >> resp;   cout << endl << endl; } // program_id:          struct4.cpp // author:         don voils // date written:    08/31/2006 // // program description: This program illustrates an anonymous structure // #include<iostream> using namespace std; struct {    int theMonth;    int theDay;    int theYear; } invoiceDate; void main() {    char dash;    cout << "What is the invoice date? ";    cin >> invoiceDate.theMonth >> dash >> invoiceDate.theDay        >> dash >> invoiceDate.theYear;    cout << endl << "Did you say that the invoice date is "         << invoiceDate.theMonth << "/" << invoiceDate.theDay         << "/" << invoiceDate.theYear << endl << endl << endl;    char resp;    cout << endl << endl << "Continue? ";    cin >> resp;    cout << endl << endl; } // program_id     studentgrades2.cpp // written_by     don voils // date_written   4/12/2006 // // description    This program demonstrats the use of arrays //           of instances of a structure. #include<iostream> #include<string> using namespace std; // The header file contains the definition of the stucture // #include "quizzes.h" // The function prototypes used // int enterStudents(Quizzes students[]); void calculateAverages(Quizzes students[],int numberStudents); void clearScreen(); void main() {      clearScreen();      // The program will have an array      // of 30 instances of the structure Quizzes      //   Quizzes students[30];      // Permits the entry of information about      // all of the upto 30 students. It returns      // the exact number of students entered.      //   int numberStudents = enterStudents(students);      clearScreen();      // Calculates the average for each student and      // displays the name and average on the screen.      //   calculateAverages(students,numberStudents);      cout << endl << endl;      char resp;      cout << "Continue? ";      cin >> resp;      cout << endl << endl; } int enterStudents(Quizzes students[]) {    char resp;    int index;    for(index = 0; index < 30 ; ++index)    {      cout << "What is student " << index+ 1 << "\'s first name? ";      cin >> students[index].firstName;      cout << "What is student " << index+ 1 << "\'s last name? ";      cin >> students[index].lastName;      cout << endl;      for(int jindex = 0 ; jindex < 5; ++jindex)      {         cout << "What is " << students[index].firstName + " " + students[index].lastName              << "\'s grade on quiz " << jindex + 1 << "? ";         cin >> students[index].quizGrades[jindex];      }      resp = 'y';      if(index < 29)      {         cout << endl << "Another student (Y/N)? ";         cin >> resp;      }      if(resp =='N' || resp =='n')      {        ++index;        break;      }      clearScreen();    }    return index; } void calculateAverages(Quizzes students[],int numberStudents) {   for(int index = 0; index < numberStudents; ++ index)   {     int sumQuizzes = 0;     for(int jindex = 0; jindex < 5; ++jindex)     {       sumQuizzes += students[index].quizGrades[jindex];     }     cout << students[index].firstName + " " + students[index].lastName << "\'s average is "          << sumQuizzes/5.0 << endl ;   } } // Used to clear the screen // void clearScreen() {      for(int index = 0; index < 50;++index)           cout << endl; } // program_id     studentgrades.cpp // written_by     don voils // date_written   4/12/2006 // // description   This program demonstrats the use of arrays //               of instances of a structure. #include<iostream> #include<string> using namespace std; // The definition of the stucture // struct Quizzes {    string firstName;    string lastName;    int quizGrades[5]; }; // The function prototypes used // int enterStudents(Quizzes students[]); void calculateAverages(Quizzes students[],int numberStudents); void clearScreen(); void main() {      clearScreen();      // The program will have an array      // of 30 instances of the structure Quizzes      //   Quizzes students[30];      // Permits the entry of information about      // all of the upto 30 students. It returns      // the exact number of students entered.      //   int numberStudents = enterStudents(students);      clearScreen();      // Calculates the average for each student and      // displays the name and average on the screen.      //   calculateAverages(students,numberStudents);      cout << endl << endl;      char resp;      cout << "Continue? ";      cin >> resp;      cout << endl << endl; } int enterStudents(Quizzes students[]) {    char resp;    int index;    for(index = 0; index < 30 ; ++index)    {      cout << "What is student " << index+ 1 << "\'s first name? ";      cin >> students[index].firstName;      cout << "What is student " << index+ 1 << "\'s last name? ";      cin >> students[index].lastName;      cout << endl;      for(int jindex = 0 ; jindex < 5; ++jindex)      {        cout << "What is " << students[index].firstName + " " + students[index].lastName             << "\'s grade on quiz " << jindex + 1 << "? ";        cin >> students[index].quizGrades[jindex];      }      resp = 'y';      if(index < 29)      {        cout << endl << "Another student (Y/N)? ";        cin >> resp;      }      if(resp =='N' || resp =='n')      {        ++index;        break;      }      clearScreen();    }    return index; } void calculateAverages(Quizzes students[],int numberStudents) {   for(int index = 0; index < numberStudents; ++ index)   {     int sumQuizzes = 0;     for(int jindex = 0; jindex < 5; ++jindex)     {       sumQuizzes += students[index].quizGrades[jindex];     }     cout << students[index].firstName + " " + students[index].lastName          << "\'s average is " << sumQuizzes/5.0 << endl ;   } } // Used to clear the screen // void clearScreen() {      for(int index = 0; index < 50;++index)           cout << endl; } // program_id       the_date.cpp // author             Don Voils // date_written        08/04/2006 // program description    The date structure with //           member functions. // #include <iostream> using namespace std; struct date {      long  month,         day,         year;      void setDate()      {           char  dash;           cout << "What is the date? ";           cin >> month >> dash >> day >> dash >> year;           if(year < 10)              year += 2000;           else             if(year<100)                           year += 1900;      }      void monthName()      {           char month_name[][10] = {"","JANUARY", "FEBRUARY",                "MARCH", "APRIL", "MAY", "JUNE","JULY",                "AUGUST", "SEPTEMBER", "OCTOBER", "NOVEMBER",                "DECEMBER"};           cout << endl<< endl << "The date is " << month_name[month]                            << " " << day << ", " << year;      } }; void main() {      date aDate;      aDate.setDate();      aDate.monthName();      char resp;      cout << endl << endl << "Continue? ";      cin >> resp;      cout << endl << endl; } // program_id    theAccount.h // written_by    don voils // date_written  3/2/2006 // description   This file contains the definition //               of the structure Account. The member functions //               for the structure are placed in the //               source file: account2.cpp #ifndef ACCOUNT #define ACCOUNT struct Account {    float theBalance;    void settheBalance(float);    float gettheBalance();    void doDeposit(float);    void doWithdrawal(float); }; #endif // program_id      theAccount.h // written_by      don voils // date_written   3/2/2006 // // description    This file contains the member functions //                for the structure Account whose definition is contained //                in the header file: theAccount.h. This file //                should be a source file in the project. // #include "theAccount.h" void Account::settheBalance(float theAmount) {   theBalance = theAmount; } float Account::gettheBalance() {       return theBalance; } void Account::doDeposit(float theAmount) {    theBalance += theAmount; } void Account::doWithdrawal(float theAmount) {    theBalance -= theAmount; } // program_id     theClock.cpp // author:               DON VOILS // date written:         07/20/2006 // // program description   This program demonstrates a timer and //                        how to keep data at the same place on the //                         screen. It uses the system date and time //                         to begin the clock. // // Note: The function: putch() and kbhit() were changed to //       _putch() and _kbhit() in Visual Studio .NET 2005 //       for security reasons. // #include<iostream> #include<string> #include<conio.h> using namespace std; #include"thedate.h" long theMonth(string theString); void main() {      long  seconds=0L,          minutes=0L,          hours=0L,                      counter,          loop,          month,          day,          year;   string theTimer = __TIME__;   string theDate = __DATE__;   string Month = theDate.substr(0,3);   string Day = theDate.substr(4,2);   string Year = theDate.substr(7,4);   month = theMonth(Month);   day = (long) atoi(Day.c_str());   year = (long) atoi(Year.c_str());   date clockDate(month,day,year);   string Hours = theTimer.substr(0,2);   string Minutes = theTimer.substr(3,2);   string Seconds = theTimer.substr(6,2);   hours = atoi(Hours.c_str());   minutes = atoi(Minutes.c_str());   seconds = atoi(Seconds.c_str());   // This clears the screen.   //   system("cls");   bool nextDay = false;   clockDate.showDate();   for(;!_kbhit();)   {      for(loop=1;loop<=8;++loop)      {         for(counter=1L;counter <=2L;++counter)              _putch('\b');         for(counter=1L;counter <=2L;++counter)              _putch(' ');         for(counter=1l;counter <=2L;++counter)              _putch('\b');      }      ++seconds;      if(seconds > 59)      {         minutes++;         seconds = 0;             }      if(minutes >59)      {         hours++;         if(hours==24)           nextDay=true;         if(hours>24)             hours = 1;         minutes = 0;      }      if(nextDay)      {               // This function clears the screen.               //               system("cls");         clockDate.next_day();               clockDate.showDate();         nextDay = false;      }      cout << " " ;      if(hours<10)           cout << "0";      cout << hours;      cout << ":";      if(minutes<10)           cout << "0";      cout << minutes;      cout << ":";            if(seconds <10)           cout << "0";      cout << seconds;      for(counter=1l;counter <= 299999999L;++counter);      } } long theMonth(string Month) {      short month;      if(Month=="Jan")         month = 1;      else         if(Month=="Feb")           month = 2;         else           if(Month=="Mar")               month = 3;           else               if(Month=="Apr")                   month = 4;               else                   if(Month=="May")                       month = 5;                   else                       if(Month=="Jun")                           month = 6;                       else                           if(Month=="Jul")                               month = 7;                           else                               if(Month=="Aug")                                   month = 8;                               else                                   if(Month=="Sep")                                       month = 9;                                   else                                       if(Month=="Oct")                                           month = 10;                                       else                                           if(Month=="Nov")                                               month = 11;                                           else                                               month = 12;      return (long) month; } // program_id         thedate.h // written_by        Don Voils // date_written      7/200/2006 // header description  This header contains the definition //                     of the class date that can be used in many //                     different examples. // // USER DEFINED DATA TYPES //  typedef int COUNTER; struct date {    long    month,          day,          year;      date();      date(long m,long d,long y);    void set_date();      void showDate();      void setMonth(long m);      void setDay(long d);      void setYear(long y);      long getMonth();      long getDay();      long getYear();      void next_day();    long days_between(date a_date);    long days_since(date a_date);    long f(date a_date);    long g(date a_date);    void find_day_of_week_for();    bool incorrect_date(date a_date);    long days_in_month(date a_date);    bool is_leap_year(date a_date); }; date::date() { } date::date(long m,long d,long y) {      month = m;      day = d;      year = y; } void date::set_date() {   date a_date;   char dash;   int theCount = 0;   do   {        a_date.month = 0L;        a_date.day = 0L;        a_date.year = 0L;          if(theCount==0)             cout << endl << endl << "FINDING THE DAY OF THE WEEK"                << endl << endl;          else             cout << endl << endl <<"Error in entering date. Please try again. "                << endl << endl;        month = 0L;        day = 0L;        year = 0L;        cout << "What is the date? MM/DD/YY ";        cin >> month >> dash >> day >> dash >> year;       if(year<10)             year = year + 2000L;       else          if(year < 100)               year = year + 1900L;       a_date.month = month;       a_date.day = day;       a_date.year = year;       ++theCount;   } while(incorrect_date(a_date)); } void date::find_day_of_week_for() {   date a_date;   int number;   a_date.month=month;   a_date.day=day;   a_date.year=year;   string day_name[7]= {"Saturday", "Sunday", "Monday", "Tuesday",                   "Wednesday", "Thursday", "Friday"};      string month_name[13]={"","January", "February", "March", "April",                        "May", "June", "July", "August",                        "September", "October", "November", "December"};   number = (int)(days_between(a_date) % 7L);   cout << endl << endl << month_name[month] << " " << day << ", "     << year << " was a " << day_name[number] << endl << endl; } void date::showDate() {   date a_date;   int number;   a_date.month=month;   a_date.day=day;   a_date.year=year;   string day_name[7]= {"Saturday", "Sunday", "Monday", "Tuesday",                   "Wednesday", "Thursday", "Friday"};      string month_name[13]={"","January", "February", "March", "April",                        "May", "June", "July", "August",                        "September", "October", "November", "December"};   number = (int)(days_between(a_date) % 7L);   cout << day_name[number] << " " << month_name[month] << " " << day << ", "      << year << endl; } void date::setMonth(long m) {      month = m; } void date::setDay(long d) {      day = d; } void date::setYear(long y) {      year = y; } long date::getMonth() {      return month; } long date::getDay() {      return day; } long date::getYear() {      return year; } long date::days_between(date day) {    date t_date;    t_date.month=11L;    t_date.day=24L;    t_date.year=1934L;    long number = days_since(day) - days_since(t_date);    return(number); } long date::days_since(date a_date) {    long number = 1461L*f(a_date)/4L + 153L*g(a_date)/5L + a_date.day;    return(number); } long date::f(date a_date) {    long number = (a_date.month<=2L) ? a_date.year - 1L : a_date.year;    return(number); } long date::g(date a_date) {    long number = (a_date.month<=2L) ? a_date.month + 13L :                    a_date.month + 1L;    return(number); } bool date::incorrect_date(date a_date) {    bool bad_date;    if (((a_date.month>=1L) && (a_date.month<=12L)) &&        ((a_date.day>=1L) && (a_date.day<=days_in_month(a_date))))        bad_date = false;    else        bad_date = true;    return(bad_date); } long date::days_in_month(date a_date) {    int upper_limit;    long days_in_month[] = {0L, 31L, 28L, 31L, 30L, 31L, 30L,                   31L, 31L, 30L, 31L,30L, 31L};      if (a_date.month != 2L)       upper_limit = days_in_month[a_date.month];      else       if (is_leap_year(a_date))           upper_limit = 29L;       else           upper_limit = days_in_month[a_date.month];    return (upper_limit); } bool date::is_leap_year(date a_date) {    bool a_leap_year;    if (((a_date.year%4L == 0L)&&(a_date.year%100L != 0L))        || (a_date.year%400L == 0L))        a_leap_year = true;    else        a_leap_year = false;    return(a_leap_year); } void date::next_day() {      date a_date(month,day,year);      if(day+1 <= days_in_month(a_date))           day++;      else        if(month+1<=12)        {            day = 1;            month++;        }        else        {            day = 1;          month = 1;            year++;        } } //   program_id         typedef1.cpp //   author           don voils //   date_written       08/31/2006 // //   program description   A program to test whether typedef //                                can have be used for I/O. // #include<iostream> using namespace std; typedef int Boolean; void main() {      Boolean closeQuarter;            cout << "Should we close the quarter? (0=NO, 1=YES)";      cin >> closeQuarter;      if (closeQuarter)            cout << endl << "Closing quarter!";      else            cout << endl << "Not closing quarter now!";      char resp;      cout << endl << endl << "Continue?";      cin >> resp;      cout << endl << endl; } 




Intermediate Business Programming with C++
Intermediate Business Programming with C++
ISBN: 738453099
EAN: N/A
Year: 2007
Pages: 142

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net