Lecture 4 Examples


image from book

Open table as spreadsheet

Program

Demonstrates

BYREF.CPP

Demonstrates passing by reference a variable into a function thereby being not changing the value of a local variable.

BYVALUE.CPP

Demonstrates passing by value a variable into a function thereby being not changing the value of a local variable.

DEFLTMSG.CPP

Shows how to use default functions to create a message system.

DEFLTVLU.CPP

Shows how default values can be used with a function.

externalheader.h

This file contains a call to an external variable defined in the program external.cpp. It demonstrates how external variable work.

external.cpp

Demonstrates both external and static variables. External variables are global and may be shared between different files of the program. Static variable may be global but they may not be shared between files of the program.

gender.cpp

This program is used for debugging and testing.

Design file for the program: gender.cpp:

pc_gender_grades

This is a design file to be used in writing the program: gender.cpp

Design file for the program: banking.cpp

pc_banking

This is a design file to be used in writing the program: banking.cpp

INLINE1.CPP

Compares the use of #define with the concept of inline and illustrating why in some cases inline is a better technique.

INLINE2.CPP

Demonstrates the use of inline functions

MAINARG.CPP

Shows non-void arguments for main( )

MONEY.CPP

Shows arguments of pointers.

NEWFACT.CPP

Demonstrates the use of recursive functions to solve problems.

NEWGCD.CPP

Demonstrates the concept of recursion.

NEWNAME.CPP

Shows arguments and output of pointers.

OVERLOAD.CPP

This is an example of overloading the function name MAX() to demonstrate the concept.

OVERLOD2.CPP

Demonstrates the use of overloaded functions. Notice ambiguity between char and int arguments.

OVERLOD3.CPP

Demonstrates what happens when functions are overloaded and the arguments do not have an exact match. It demonstrates the concept of promotion.

payables.cpp

This program is used for testing the compiler.

Design files for the program population.cpp:

sc_population.gif

pc_population.txt

These files are used as design documents in an example of how to approach coding of a program with modules using the design documents.

REGISTER.CPP

Demonstrates the use of the storage class register.

SCOPE1.CPP

Demonstrates that variables within a function are distinct from those external from the function.

SCOPE2.CPP

Demonstrates that an automatic variable within a function takes precedence over a global variable name.

SCOPE3.CPP

Demonstrates that two different functions can have a variable with the same name as a global variable yet all be distinct from each other.

SCOPPRTR.CPP

Demonstrates that variables within a function are distinct from global variable but that using the scope resolution operator the global variables can be accessed within the function.

STATIC1.CPP

Demonstrates the use of static variables with global variables.

image from book

 // program_id         byref.cpp // author             don voils // date written      09/22/2006 // program description:  This program demonstrats passing by //                         reference a variable into a //                         function thereby being not changing //                         the value of a local variable. // #include<iostream> using namespace std; void byref(long &p,long &q); void main(void) {    long  i = 734545,         j = 323423;    cout << "Before passing to by reference " << i         << " and " << j << endl << endl;    byref(i,j);    cout << "After passing to by reference " << i         << "and " << j << endl << endl; } void byref(long &p,long &q) {       ++p;       ++q;       cout << "Inside of by reference " << p            << " and " << q << endl << endl; } // program_id         byvalue.cpp // author             don voils // date written      10/14/89 // date modified      09/22/2006 // // assignment: // // hardware requirements:  PS/2 //                          4 Mb Ram //                          100 Mb harddrive //                          VGA monitor // // software requirements:  Windows 3.1 //                          MS-DOS 5.0 // // program description:   This program demonstrats passing by //                         value a variable into a function //                         thereby being not changing the //                         value of a local variable. #include<iostream> using namespace std; void byvalue(long p,long q); void main(void) {    long  i = 734545,         j = 323423;    cout << "Before passing to by value " << i         << " and " << j << endl << endl;    byvalue(i,j);    cout << "After passing to by value " << i         << " and " << j << endl << endl; } void byvalue(long p,long q) {       ++p;       ++q;       cout << "Inside of by value " << p            << " and " << q << endl << endl; } // program_id           DEFLTMSG.CPP // author               don voils // data written        9/23/2006 // // program description     This example shows how to use //                          default functions to create a //                          message system. #include<iostream> using namespace std; // The declaration show that this function // has a default value. // void printMessage(char note[]="Turn printer on"); void main(void) {    char driveMessage[]="Abort, Retry, Ignore, Cancel?";    for(int counter=1;counter<=25;++counter)       cout << endl;    cout << flush;    // This call of the function uses the default value.    // for the arugument.    //    printMessage();    // This call of the function does not use the default value.    printMessage(driveMessage);    cout << endl << endl; } // The definition of the function does not show any default // arguments. // void printMessage(char* note) {    cout << endl << endl << note << endl; } // program_id            DEFLTVLU.CPP // author                don voils // date written         9/23/2006 // // program description      This program shows how default //                           values can be used with a function. // #include<iostream> using namespace std; // Notice that this declaration contains // two default arguments on the right site. // int f(int a, int b, int c=6, int d=10); void main(void) {    // Notice in the following code the fact that f() has default values    // is not apparent from the call.    //    int y;    cout << "The output value is the sum of the four arguments." << endl         << endl;    cout << "The values are a = 5 and b = 6 with c "         << "defaulting to 6 and d defaulting to 10" << endl;    y = f(5,6);        // a and b are passed the values                   // 5 and 6 respectively. c and d                   // are given the default values                   // 6 and 10 respectively.    cout << "Then the value of the output is " << y << endl         << endl;    cout << "The values are a = 5, b = 6 and c = 7"         << " and d defaults to 10" << endl;    y = f(5,6,7);      // a, b, and c are passed the                   // values 5, 6, and 7 respectively.                   // d is given the default value 10.    cout << "Then the value of the output is " << y << endl << endl;    cout << "The values are a = 5, b = 6, c = 7 "         << " and d = 8 with no defaults." << endl;    y = f(5,6,7,8);       // a, b, c, and d are passed the                     // values 5, 6, 7, and 8                     // respectively.    cout << "Then the value of the output is " << y << endl << endl; } // Notice that while the declaration above of this function // contained default values, this definition does not indicate // the the right two arguments have default values. // int f(int a, int b, int c, int d) {     return a+b+c+d; } // program_id    external.cpp // written_by   don voils // date_written 3/31/2006 // description  This program demonstrates both external and static variables. //              External variables are global and may be shared between //              differrent files of the program. Static variable may be global //              but they may not be shared between files of the program. // #include<iostream> using namespace std; #include"externalheader.h" int theExternal = 7; static int theStatic = 8; void main() {      cout << "At the start of main(), theExternal = " << theExternal                 << endl << endl;      cout << "At the start of main(), theStatic = " << theStatic                 << endl << endl;      theExternal = 15;      theStatic = 45;      cout << "In the middle of main(), theExternal = " << theExternal                 << endl << endl;      cout << "In the middle of main(), theStatic = " << theStatic                 << endl << endl;      cout << "Inside main() and the call to change the external "                 << changeExternal() << endl << endl; } // program_id    externalheader.h // written_by    don voils // date_written 3/31/2006 // description  This file contains a call to an external //              variable defined in the program external.cpp. //              It demonstrates how external variable work. // // The following variable was defined in the file: exteranl.cpp. // It was just defined as a global variable but no explicit // storage class was used. Therefore by default the variable // was external. To use this variable in this file, it needed // to have the storage class: extern used to notify the // compiler that the variable theExternal had been defined // in another file of the program. If the keyword extern is // removed, the program will not compile because the variable // would be redefined in this file. // extern int theExternal; // The following variable was defined as a global variable that // had a storage class of an static variable in the file: external.cpp. // Therefore this variable may not be used in this file. // // int theStatic; // int changeExternal() {       // This variable may not be changed in this flie.       // theStatic = 55;       cout << "Before the change of the external inside changeExternal() "                  << theExternal << endl << endl;       theExternal = 20;             cout << "Change the external inside changeExternal() " << theExternal                  << endl << endl;     return theExternal; } // program_id   gender.cpp // written_by   don voils // date_written 11/11/2006 // description  Used to demonstrate how to debug. // #include<iostream> #include<fstream> #include<iomanip> using namespace std;   // The function declarations   // void initialization(); void read_file(); void transfer_data(); void print_report(); void print_heading(); void print_detail_line(); void print_total_line();   // The following definitions makes these variables global   // so that they may be accessed in each function.   // short index1,    index2; double GRADES[9],     femaleGPA,     maleGPA; void main() {   initialization();   read_file();   transfer_data();   print_report();   cout << endl << endl << "Continue? ";   char resp;   cin >> resp;   cout << endl << endl; }   // This program initializes the totals.   // void initialization() {   female_GPA = 0.00,   male_GPA = 0.00; }   // This function inputs the data and stores it into   // the double array GRADES[]. void read_file() {      //      // Set up the file to be read      //   ifstream infile("list.txt");   if(!infile)   {      cout << "File did not open. " << endl << endl;      exit(1);   }      //      //    Read in the records from the file into the array GRADES[]      //   for(index1=0;index1<9;++index1)   {     infile >> GRADES[index1];   }      //      // This closes the file since      // it is not longer needed for the program.   infile.close(); }   // This function processes the report by calling the   // functions for the heading, the detail line and the   // total line. void print_report() {   print_GPA();   print_female_gpa();   print_male_gpa(); }   //   // This function outputs the heading of the report   // The function set() is used to set up columns.   // void print_heading() {   cout << setw(60) << "The Reversing a List Problem    "        << endl        << setw(20) << "Index"        << setw(20) << "Gender Grades"        << setw(20) << "REVERSE Elements" << endl; }   //   // This function outputs the elements in the t arrays in the order   // from first element until the last element.   //   // In addition the elements of the   // void print_detail_line(); {      //      // Force the double output to display a decimal point      // in fixed decimal notation rather than scientific notation.      //    cout.setf(ios::fixed);    for(index1=0;index1<9;++index1)    {      cout << setw(20) << index1           << setw(20) << setprecision(2) << GRADES[index1]           << setw(20) << setprecision(2) << REVERSE[index1] << endl;      female_GPA = sumFemaleMathGPA + GRADES[index1];      male_GPA = sumMaleMathGPA + GRADES[index2];    } }   //   // This function outputs the column totals.   // void print_total_line() {   cout << setw(20) << " "        << setw(20) << "---------"        << setw(20) << "---------" << endl        << setw(20) << "Totals"        << setw(20) << setprecision(2) << female_GPA        << setw(20) << setprecision(2) << male_GPA << endl; } // program_id      generalLedger.cpp // written_by      Don Voils // date_written    06/26/2006 // // description    This program demonstrates how to pass multidimentional //                 arrays to functions as arguments. // #include<iostream> #include<iomanip> #include<string> using namespace std;   // Constants used to control the arrays   // const short numberMonths = 12; const short numberAccounts = 5;   // Function declarations   // void clearScreen(); void enterAmounts(double generalLedger[][numberAccounts],string theMonths[]); void displayAmounts(double generalLedger[][numberAccounts],string theMonths[],short numberMonths,short numberAccounts);   // Definitions of enumerated data types used to control arrays.   // enum Months {January, February, March, April,             May, June, July, August,       September, October, November, December}; enum Accounts {First, Second, Third, Fourth, Fifth}; void main() {      short resp;      bool continueProgram = true;      string theMonths[]= { "January", "February", "March", "April",                                   "May", "June", "July", "August",                                   "September", "October","November","December"};      double generalLedger[numberMonths][numberAccounts] =                                         {{0.00,0.00,0.00,0.00,0.00}};      do      {               clearScreen();        cout << "General Ledger" << endl << endl                   << "1. Enter Amounts" << endl                   << "2. Display Amounts" << endl                   << "3. Quit " << endl << endl;        cin >> resp;        switch(resp)               {                case 1:                  clearScreen();                  enterAmounts(generalLedger,theMonths);                  break;                case 2:                  clearScreen();                  displayAmounts(generalLedger,theMonths,                  numberMonths,numberAccounts);                  break;                case 3:                  clearScreen();                  continueProgram = false;                  break;                 default:                  break;               }     }while(continueProgram); } void clearScreen() {      for(short index = 0; index <=50; ++index)           cout << endl; } void enterAmounts(double generalLedger[][numberAccounts],string theMonths[]) {      for(Months indexMonths = January; indexMonths <= December;                                  indexMonths = static_cast<Months>(indexMonths + 1))      {          cout << endl << "Enter the amounts for "                            << theMonths[indexMonths] << endl;          for(Accounts indexAccounts = First; indexAccounts <= Fifth;                             indexAccounts = static_cast<Accounts>(indexAccounts + 1))          {            cout << "The amount for account #"                 << static_cast<int>(indexAccounts+1) << " ";                  cin >> generalLedger[indexMonths][indexAccounts];          }      }      cout << endl << endl                 << "All of the General Ledger Accounts have been entered."                 << endl;            cout << "Continue? ";            char resp;            cin >> resp; } void displayAmounts(double generalLedger[][numberAccounts],                       string theMonths[],short numberMonths,short numberAccounts) {      cout << fixed << setprecision(2);            double totalLedger = 0.00;      for(short indexMonths = 0; indexMonths < numberMonths; ++indexMonths)             {                double totalAccountAmount = 0.00;                cout << endl << "The amounts for "                     << theMonths[indexMonths] << endl;                for(short indexAccounts = 0; indexAccounts < 5; ++indexAccounts)                {                  cout << "The amount for account #"                       << (indexAccounts+1) << " $"                << setw(8)                      << generalLedger[indexMonths][indexAccounts]                      << endl;                 totalAccountAmount += generalLedger[indexMonths][indexAccounts];                }                cout << "              __________" << endl;                cout << "Total amount for " << theMonths[indexMonths]                     << " $" << setw(8) << totalAccountAmount                     << endl << endl;                totalLedger += totalAccountAmount;             }     cout << endl << "General Ledger Total $"                  << setw(8) << totalLedger << endl << endl;     char resp;     cout << "Continue? ";     cin >> resp; } // program_id       INLINE1.CPP // author           don voils // date written    9/24/2006 // // program description This program compares the use of #define //                      with the concept of inline and //                      illustrating why in some cases inline //                      is a better technique. // #include <iostream> using namespace std; const float RATE = 0.06F; #define sales_tax(x) x*RATE #define clear_screen() {for(int i = 0;i <= 25; ++i) {cout << endl; cout << flush;}} inline float SALES_TAX(float x) {return x*RATE;} //   If you try to compile this a warning may be issued saying //   that a function request for inline expansion with the for //   construct will not be expanded. In this case it is treated //   just like a functional definition. Frequently a function //   with the for construct will not be expanded inline. // inline void CLEAR_SCREEN(void) {for(int j=0;j<=25;++j) cout << endl; cout << flush;} void main(void) {   char resp;   float x=500.00, y=600.00;   cout << "This is the start:" << endl;   cout << endl << "Continue? (y/n)";   cin >> resp;   clear_screen();   cout << "The result of using #define yields " << endl <<endl        << "The sales tax of " << x << " is " << sales_tax(x)        << endl << endl        << "while the sales tax of " << x << " plus "        << y << " is " << sales_tax(x+y) << endl << endl        << "The result of using inline yields " << endl <<endl        << "The sales tax of " << x << " is " << SALES_TAX(x)        << endl << endl        << "while the sales tax of " << x << " plus "        << y << " is " << SALES_TAX(x+y);   cout << endl << endl << "This is the end of the program.";   cout << endl << "Continue? (y/n)";   cin >> resp;   CLEAR_SCREEN();   cout << "After the screen is cleared by the "        << "inline clear screen" << endl; } // program_id           INLINE2.CPP // author               don voils // date written        9/24/2006 // // program description     This program demonstrates the use //                          of inline functions. // #include<iostream> using namespace std; inline double MAX(double x, double y) {    return ((x>y)?x:y); } inline bool good_fraction(long numerator,long denominator) {    bool response;    if (denominator==0)    {        cout << endl << endl             << "A zero denominator is not permissible."             << endl << endl;        response = false;    }    else       response = true;    return response; } void main(void) {    double  a=50000.0,            b=60000.0,            c;    long    i=50000,            j=0;    c = MAX(a,b);    cout << "The maximum of " << a << " and " << b         << " is " << c << endl << endl;    cout << "The numerator is " << i << " and "         << " the denominator is " << j << endl << endl;    while(good_fraction(i,j)==false)    {       cout << endl << "What is the numerator? ";       cin >> i;       cout << endl << endl << "What is the denominator? ";       cin >> j;    }    cout << endl<< "That is a good fraction." << endl; } // program_id mainarg.cpp // author             don voils // date written      9/22/2006 // // // program description   Shows non-void arguments for main() // // Comment:            Compile this program. After compiling you will have mainarg.exe. //                       At the command line type in the following: //                       mainarg.exe /t Florida // #include<iostream> #include<string> using namespace std; void main(int argc,char *argv[]) {  cout << "The program name is "<< argv[0] << endl;  for(int index = 1 ; index < argc; ++ index)  {      if(argv[index][0]=='/')      {           switch(argv[index][1])           {           case 't':                 cout << "Do not use the title page" << endl;                 break;           case 'd':                 { int numb = strlen(argv[index]);                  cout << "The directory is ";                  for(int jndex=2; jndex < numb;++jndex)                  {                     cout << argv[index][jndex];                  }                 }                 cout << endl;                break;           default:                cout << "The flag did not work" << endl;                break;           }       }       else        cout << "The next string is " << argv[index] << endl;  } } // program_id     money.cpp // author                don voils // date written          9/22/2006 // program description   Shows arguments of pointers. // // #include<conio.h> #include<iostream> #include<string> using namespace std; void format_d(char *&new_money,char* money) {      int index,          counter,          length,          count_decimals=0;      char catcher=' ';             bool got_period = false;      char *int_money = new char[strlen(money)+1];      for(index=0;((index<(int)strlen(money)) && (catcher !='.'));++index)      {           catcher = money[index];           if(catcher!='.')           {                int_money[index] = catcher;                        }           else                        {                --index;                  }      }             int_money[index]='\0';      bool do_comma;      length = (int)strlen(int_money);      index = 0;      new_money[index]='$';           ++index;      for(counter=0;counter<(int)strlen(money);++counter,++index)      {           catcher = money[counter];           if((got_period) && (catcher == '.'))           {                --index;                continue;           }           if(got_period)                 ++count_decimals;           new_money[index] = catcher;           if(catcher=='.')                 got_period = true;                         do_comma = false;                  switch(length)                  {                 case 4:                          if(index==1)                                                    do_comma = true;                          break;                                    case 5:                          if(index==2)                       do_comma = false;                          break;                 case 6:                          if(index==3)                       do_comma = true;                          break;                 case 7:                          if((index==1) || (index==5))                       do_comma = true;                          break;                 case 8:                          if((index==2) || (index==6))                       do_comma = true;                          break;                 case 9:                          if((index==3) || (index==7))                       do_comma = true;                          break;                 case 10:                          if((index==1) || (index==5)                          || (index==9))                       do_comma = true;                         break;                        }                  if(do_comma)                         {                           ++index;                new_money[index] = ',';                  }     }     if((got_period) && (count_decimals<2))     {           for(counter=index;count_decimals<2;++counter)                        {                new_money[counter] = '0';                ++count_decimals;                ++index;                       }            }     new_money[index]='\0';          delete int_money; } void main() {          int index,      extra;         char *money = new char[50],       catcher;        do        {         cout << "What is the number? ";         index = 0;         catcher = getche();         while((catcher!='\n') && (catcher!=' '))         {      money[index] = catcher;           catcher = ' ';      catcher = cin.get();            ++index;          }          money[index]='\0';         if((int)strlen(money)<4)      extra = 1;          else       if((int)strlen(money)<7)           extra = 2;       else          if((int)strlen(money)<10)              extra = 3;                  else              extra = 4;          char * new_money = new char[strlen(money)+extra];          format_d(new_money,money);          cout << new_money;          cout << endl << endl << "Do another one? ";          cin.get(catcher).get();     }while((catcher=='y') || (catcher=='Y'));     delete money; } // program_id           NEWFACT.CPP // author               don voils // date written        9/24/2006 // // program description     This program demonstrates the use //                          of recursive functions to solve problems. #include<iostream> using namespace std; unsigned long factorial(int); void main() {    int number1;    cout << "What is the number? ";    cin >> number1;    if(number1 > 30)    {          cout << endl << endl << "That number is too large."               << endl << endl; }    else    {          cout << endl << endl << number1 << " factorial is "               << factorial(number1) << endl << endl;    } } // Notice that this function calls itself. Therefore // this is an example of a recursive function. // unsigned long factorial(int numb) {    return (numb==0)?(1):(numb * factorial(numb-1)); } // program_id       NEWGCD.CPP // author           don voils // date written    9/24/2006 // // program description This program demonstrates the concept //                      of recursion by revising GCD.CPP. // #include <iostream> using namespace std; int new_gcd(int numb1, int numb2); void main(void) {    int int1,        int2;    cout << "What is the first number? ";    cin >> int1;    cout << endl << endl << "What is the second number? ";    cin >> int2;    cout << endl << endl << "The GCD of " << int1 << " and "         << int2 << " is " << new_gcd(int1,int2);     cout << endl << endl; } // Notice that the body of this function contains a // call to the function. Therefore this is an // example of a recursive function. // int new_gcd(int numb1, int numb2) {     return (numb1<0) ? new_gcd(-numb1,numb2):((numb2==0)?                            numb1:new_gcd(numb2,numb1%numb2)); } // PROGRAM_ID          NEWNAME.CPP // author                don voils // date written          9/22/2006 // program description   Shows arguments and output of pointers // // // #include<iostream> #include<string> using namespace std; void newname(char * thename,char* first, //   is the first name          char* second); // is the second name void main() {      char* first = new char[10];      char* last = new char[15];      char* thename = new char[25];      char catcher;      cout << endl << "What is the first name ";      cin >> first;      cout << endl << "What is the last name ";      cin >> last;      newname(thename,first,last);      cout << endl << endl << "The name is " << thename << endl << endl;      delete [] first;      delete [] last;      delete [] thename;      cout << endl << "Continue? (Y)";      cin >> catcher; } void newname(char* thename,char* first, char* second) {      char temp2[4] = ", ";      temp2[2]=first[0];      strcpy(thename,second);      strcat(thename,temp2); } // program_id          OVERLOAD.CPP // author              don voils // date written       9/23/2006 // // program description    This is an example of overloading //                        the function name MAX() to //                        demonstrate the concept. // #include <iostream> using namespace std; //   FUNTIONAL PROTOTYPES FOR THE OVERLOADED MAX // int MAX(int a, int b); long MAX(long a, long b); float MAX(float a, float b); double MAX (double a, double b); long double MAX (long double a, long double b); void main(void) {  int int1=5, int2=6;  long long1=50000, long2= 60000;  float float1=5.0, float2=6.0;  double double1=500000.0, double2=600000.0;  long double long_double1 = 500000000.0, long_double2=600000000.0;  cout << "This is a test of overloading the functional name MAX"       << endl << endl << endl       << "The maximum of the integers " << int1 << " and " << int2       << " is " << MAX(int1,int2) << endl << endl       << "The maximum of the longs " << long1 << " and " << long2       << " is " << MAX(long1,long2) << endl << endl       << "The maximum of the floats " << float1 << " and " << float2       << " is " << MAX(float1,float2) << endl << endl       << "The maximum of the doubles " << double1 << " and " << double2       << " is " << MAX(double1,double2) << endl << endl       << "The maximum of the long doubles " << long_double1 << " and "       << long_double2 << " is " << MAX(long_double1,long_double2)       << endl << endl; } int MAX(int a, int b) {    return (a>b?a:b); } long MAX(long a, long b)  {    return (a>b?a:b); } float MAX(float a, float b) {    return (a>b?a:b); } double MAX (double a, double b) {   return (a>b?a:b); } long double MAX (long double a, long double b) {    return (a>b?a:b); } // program_id       OVERLOD2.CPP // author           don voils // date written    9/24/2006 // // program description This program demonstrates the use of //                      overloaded functions. Notice ambiguity //         between char and int arguments. // #include<iostream> using namespace std; // FUNCTIONAL PROTOTYPES FOR THE OVERLOADED FUNCTION print() // void print(char * x); void print(char x); void print(int x); void main(void) {    unsigned int a=35000;    cout << "Outputting as a string is ";    print("a");    cout << endl << endl << "Outputting as a character is ";    print('a');    cout << endl << endl << "Outputting as an unsigned integer is ";    // The following will not compile because of the ambiguity    //    //   print(a);    cout << endl << endl; } void print(char * x) {    cout << x; } void print(char x) {    cout << x; } void print(unsigned int x) {    cout << x; } // program_id       OVERLOD3.CPP // author           don voils // date written    9/24/2006 // // program description This program demonstrates what happens //                      when functions are overloaded and the //                      arguments do not have an exact match. //                      It demonstrates the concept of promotion. // #include<iostream> using namespace std; // FUNCTIONAL PROTOTYPES OF THE OVERLOADED FUNCTION ff() // void ff(int); void ff(char*); void main(void) {    cout << "The output: " << endl << endl;    ff('a');    cout << endl << endl; } void ff(int x) {    cout << "This is the integer " << x << endl; } void ff(char* x) {    cout << "This is for the string " << x << endl; } // program_id    payables.cpp // written_by    don voils // date_written 2/2/2006 // description  used to test the compiler for debugging. #include <iostream> #include <iomanip> #include <string> #include <fstream> #include<conio.h> using namespace std; int main() {      string companyName;      string customerAccountNumber;      double beginningBalance=0;      string supplier;      int invoice=0;      double payment=0;      double endingBalance =0;      char inputType;      int resp;      do      {            cout<< " To enter an INVOICE press I ";            cout<< endl;            cout<< " To enter a PAYMENT press P ";            cin >> inputType;            if (inputType=I)                  input=invoice;            else                  input=payment;            cout<< " To continue press 1 to quit press 2 ";            cout<< endl;            cin >> resp;      }      while (resp = 1)      return 0; } //   program_id     pc_banking //   written_by     don voils //   date_written   4/2/2006 // Banking           Set savingsMinimumBalance = 1000           Set checkingMinimumBalance = 500           Set savingsServiceCharge = 10           Set checkingServiceCharge = 15           Set savingsInterest = .04           Set checkingLowerInterest = .03           Set checkingHigherInterest = .05           Set checkingBalanceLimit = 5000 + checkingMinimumBalance     Request customerAccountNumber     Request typeAccount     Request currentBalance     IF(typeAccount=='c')THEN          IF(currentBalance<checkingMinimumBalance) THEN                           Set serviceCharge = checkingServiceCharge                           Set interestEarned = 0                       ELSE                         Set serviceCharge = 0                         IF(currentBalance<checkingBalanceLimit) THEN                           Set interestRate = checkingLowerInterest                         ELSE                           Set interestRate = checkingHigherInterest                         ENDIF                         Calculate interestEarned = currentBalance * interestRate                       ENDIF          ELSE            IF(currentBalance<savingsMinimumBalnce) THEN             Set serviceCharge = savingsServiceCharge               Set interestEarned = 0             ELSE               Set serviceCharge = 0         Calculate interestEarned = currentBalance * savingsInterest             ENDIF          ENDIF          Calculate closingBalance = currentBalance - serviceCharge + interestEarned          Display customerAccountNumber, typeAccount, currentBalance,                            serviceCharge, interestEarned, closingBalance END //  program_id    pc_gender_grades //  written_by    don voils //  date_written  3/3/2006 // GENDERGRADES   SET numberFemaleStudents = 0   SET numberMaleStudents = 0   SET sumFemaleGPA = 0   SET sumMaleGPA = 0   OPEN gender_grades.txt   IF(NOT OPEN)THEN      DISPLAY ERROR MESSAGE      EXIT   (ELSE)   ENDIF   READ genderType   DOWHILE(NOT END OF FILE)    READ GPA    IF(genderType=='f')THEN      Calculate sumFemaleGPA = sumFemaileGPA + GPA      Calculate numberFemaleStudents = numberFemaleStudents + 1    ELSE     Calculate sumMaleGPA = sumMaleGPA + GPA     Calculate numberMaleStudents = numberMaleStudents + 1    ENDIF    READ genderType   ENDDO   CLOSE gender_grades.txt   Calculate averageFemleGPA = sumFemaleGPA/numberFemaleStudents   Calculate averageMaleGPA = sumMaleGPA/numberMaleStudents   Display the title of the report "Gender GPA Report"   Display the two column headers "Student Type", "Average GPA"   Display in two columns the word "Female", averageFemaleGPA to two decimal places   Display in two columns the word "Male", averageMaleGPA to two decimal places END //   program_id    pc_population //   written_by    don voils //   date_written  2/3/2006 // POPULATION   DO    DO     DISPLAY REQUEST FOR STARTING POPULATION     RECEIVE startingPopulation     IF(startingPopulation>=2) THEN       Set inaccurateData = false     ELSE      Set inaccurateData = true      DISPLAY ERROR MESSAGE     ENDIF    WHILE(inaccurateData)    DO     DISPLAY REQUEST FOR BIRTH RATE     RECEIVE birthRate     IF(birthRate>=0) THEN       Set inaccurateData = false     ELSE      Set inaccurateData = true      DISPLAY ERROR MESSAGE     ENDIF    WHILE(inaccurateData)    DO     DISPLAY REQUEST FOR DEATH RATE     RECEIVE deathRate     IF(deathRate>=0) THEN       Set inaccurateData = false     ELSE      Set inaccurateData = true      DISPLAY ERROR MESSAGE     ENDIF    WHILE(inaccurateData)    DO     DISPLAY REQUEST FOR NUMBER YEARS OF STUDY       RECEIVE numberYears       IF(numberYears>=2) THEN         Set inaccurateData = false       ELSE        Set inaccurateData = true        DISPLAY ERROR MESSAGE       ENDIF      WHILE(inaccurateData)      Set ePopulation = startingPopulation      Set gRate = growthRate(birthRate,deathRate)      FOR studyYear = 1 to numberYears        Set ePopulation = estimatePolulation(ePopulation,gRate);      ENDFOR      DISPLAY startingPopulation,birthRate,deathRate,numberYears,ePopulation      DO       REQUEST WHETHER TO CONTINUE WITH ANOTHER STUDY       RECEIVE RESPONSE Yes or No       IF(response != 'Y' AND response != 'y' AND response != 'N' AND response != 'n')                                                                                   THEN          ERROR MESSAGE          Set inaccurateData = true       ELSE          Set inaccurateData = false          IF(response == Y OR response == y)THEN            Set continue = true          ELSE            Set continue = false          ENDIF      while(inaccurateData)   while(continue); END growthRate(birthRate,deathRate)   Calculate gRate = birthRate - deathRate RETURN gRate estimatedPopulation(startingPopulation,gRate)    Calculate ePopulation = startingPopulation + startingPopulation * gRate / 100 RETURN ePopulation // program_id       register.cpp // author          don voils // date written    9/24/2006 // // program description This program demonstrates the use //                      of the storage class register. // // Note: putch() was replaced with _putch() for security reasons //       in Visual Studio .NET 2005 // #include<iostream> #include<conio.h> using namespace std; void main(void) {  int counter,      numb_digits;  unsigned long index,          regular_long;  cout << "The start of the regular loop:" << endl;  for(regular_long=1;regular_long<=10000;++regular_long)  {     index = regular_long;     cout << regular_long;     if (index <= 99L)       numb_digits = 2;     else       if (index <=999L)          numb_digits=3;       else         if (index <=9999L)         numb_digits=4;       else         if (index <=99999L)           numb_digits=5;         else           if (index <=999999L)             numb_digits=6;          else            if (index <=9999999L)               numb_digits=7;                  else               numb_digits=8;     for(counter=1;counter <=numb_digits;++counter)     _putch(char(8));     for(counter=1;counter <=numb_digits;++counter)     _putch(' ');     for(counter=1;counter <=numb_digits;++counter)     _putch(char(8));  }  cout << endl << endl << "The start of the register loop:"       <<endl;  for(register long register_long=1;register_long<=10000L; ++register_long)  {     index = register_long;     cout << register_long;     if (index <= 99L)         numb_digits = 2;     else       if (index <=999L)           numb_digits=3;       else          if (index <=9999L)              numb_digits=4;          else             if (index <=99999L)                 numb_digits=5;             else                 if (index <=999999L)                     numb_digits=6;             else                 if (index <=9999999L)                     numb_digits=7;                  else                     numb_digits=8;     for(counter=1;counter <=numb_digits;++counter)         _putch(char(8));     for(counter=1;counter <=numb_digits;++counter)         _putch(' ');     for(counter=1;counter <=numb_digits;++counter)         _putch(char(8));  } } // program_id    sc_population // written_by    don voils // date_written  2/2/2006 // 

image from book

 // program id      scope1.cpp // author          don voils // date written    10/16/2006 // // program description This program demonstrates that variables //                     within a function are distinct from //                     those external from the function. #include<iostream> using namespace std; void overThere(int a); void main(void) {    // This x is local to the function main().    // It also has automatic storage class.    //    int x = 5;    overThere(x);    cout << "After the function, the outside x = " << x << endl; } void overThere(int a) {    // This x is local to the function overThere().    // It also has automatic storage class.    //    int x = 7;    cout << endl << endl << "In the function, the inside x = "         << x << " and the outside x = " << a << endl << endl; } // program id      scope2.cpp // author          don voils // date written    10/16/2006 // // program description This program demonstrates that an //                      automatic variable within a function //                     takes precedence over a global variable //                     name. // #include<iostream> using namespace std; void overThere(int a); // this is an external and global variable // int x = 5; void main(void) {    overThere(x);    cout << "Outside and after the function x = " << x         << endl << endl; } void overThere(int a) {    // This is an automatic and local variable.    //    int x=7;    cout << "Inside the function the inside x = "<< x         << " and the outside x = " << a << endl << endl; } // program id       scope3.cpp // author           don voils // date written    10/16/2006 // // program description This program demonstrates that two //                     different functions can have a //                     variable with the same name as //                     a global variable yet all be distinct //                    from each other. // #include<iostream> using namespace std; void overThere(int a); void nextToThere(int a); // GLOBAL VARIABLE // int x = 5; void main(void) {    overThere(x);    cout << endl << "Outside the global x = " << x << endl << endl << endl;    nextToThere(x);    cout << endl << "Outside the global x = " << x << endl; } void overThere(int a) {    // This x is a local and automatic variable. It hides the    // global variable defined above.    //    int x;    x = 7;    cout << "Inside the local x= " << x << " & the passed by value x = " << a         << endl << endl; } void nextToThere(int a) {    // This x is not defined inside of this function so    // it is using the global variable defined above    // all of the functions.    //    x = 8;    cout << "Inside the global x = " << x << " & the passed by value x = "         << a << endl << endl; } // program id      SCOPPRTR.CPP // author          don voils // date written    10/16/2006 // // program description This program demonstrates that variables //                     within a function are distinct from //                     global variable but that using the scope //                     resolution operator the global variables //                    can be accessed within the function. // #include<iostream> using namespace std; void over_there(int a); // This is a global and external variable. // int x = 30; void main(void) {    cout << "Before the function the global x = " << x << endl;    over_there(x);    cout << "After the function the global x = " << x << endl; } void over_there(int a) {    // This is a local automatic variable.    //    int x = 7;   // Using the scope resolution operator, the global variable   // can be accessed by overruling the local x defined above.   //   ::x += 5;   cout << endl << endl << "5 was added to the global value "        << endl << endl << "The inside x = " << x        << endl << endl <<"& the passed in by value x = " << a        << endl << endl        << "& the value on the global variable as a result on the "        << endl << endl        << "scope resolution operator x = " << ::x << endl << endl; } // program id      STATIC1.CPP // author          don voils // date written    10/16/2006 // // program description This program demonstrates the use //                      of static variables with global //                      variables. // #include<iostream> using namespace std; void overThere(int a); // GLOBAL VARIABLE // int x = 5; void main(void) {    overThere(x);    cout << "Global variable outside x = " << x << endl << endl;    overThere(x);    cout << "Global variable outside x = " << x << endl << endl; } void overThere(int a) {    // Local and static variable.    //    static int x = 7;    cout << "Local static variable x= " << x << " and passed by value x = "         << a << endl << endl;    ++x;    cout << "Incremented local static variable inside." << 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