CSCI 15A Jim Murphy In addition to the while loop C++ also has a for statement and a do...while construct for (counter=initial; loop-test; repeated-statement) { iterative part } After the counter is initialized, the loop-test is evaluated and if true the iterative-part is executed and the repeated-statement is executed then the loop-test is applied again - this continues until false The code on page 281 shows that the counter could be a float or any other type not just an int src/p281.cpp // Declare and use a float for the counter of a for loop #include #include #include "ourstuff.h" float f(float x) { return x - cos(x); } int main() { cout << endl << " x | f(x) "; cout << endl << "------+--------" << endl; decimals(cout, 2); for(float x = 0; x <= 2; x = x + 0.5) { cout.width(6); decimals(cout, 1); cout << x << " |"; cout.width(7); decimals(cout, 4); cout << f(x) << endl; } return 0; } Execute with p281 x | f(x) ------+-------- 0.0 |-1.0000 0.5 |-0.3776 1.0 | 0.4597 1.5 | 1.4293 2.0 | 2.4161 Page 282 shows code where the value used in the loop test is passed as a parameter src/p282.cpp // Call produceAverage to illustrate for loops need to // know the number of repetitions before they are // encountered in the program. #include void produceAverage(int n) // In: Number of floats to be averaged { // PRE: n > 0 and no bad input is encountered in cin // POST: n floats are entered from the keyboard // and averaged float ave; // Average of n floats. float value, sum;// value: the input; sum:running sum. // Initialize sum to 0 to ensure the correct average sum = 0; for(int counter = 1; counter <= n;counter = counter+ 1) { cout << "Enter number: "; cin >> value; sum = sum + value; } // Compute and display the average ave = sum / n; cout << "Average: " << ave; } int main() { produceAverage(3); return 0; } Execute with: p282 Enter number: 57 Enter number: 38 Enter number: 76 Average: 57 C++ also provides an increment operator ++ and a decrement operator -- which allows counter = counter + 1; // to be replace with counter++; for(counter=0; counter < 10; counter++) cout << counter << endl; LESSON 13 The do while statement puts the test at the end: do { iterative-part } while (loop-test); The iterative part always executes at least once also the braces { and } are needed even for one line iterative parts - particularly good when user input is needed in the loop for initialization as on page 287 src/p287.cpp // Page 287 code has been modified #include #include"ourstuff.h"//for clearScreen and causeApause #include // for setw(32) #include // for toupper(char) void getTransaction(char & transaction) { clearScreen(); cout << "\n\n"; cout << " ATM ----------------------------------------" << endl; cout << setw(32) << "Withdraw [W]"; cout << "\n"; cout << setw(32) << " Deposit [D]"; cout << "\n"; cout << setw(32) << " Balance [B]"; cout << "\n"; cout << setw(32) << " Quit [Q]"; cout << "\n\n"; // Currently any letter pressed will be returned // as its uppercase equivalent. Only four choices // should be returned: w/W, d/D, b/B, and q/Q to quit do { cout << setw(30) << "Select [W,D,B,Q]: "; cin >> transaction; transaction = toupper(transaction); } while((transaction != 'W') && (transaction != 'D') && (transaction != 'B') && (transaction != 'Q')); } int main() { cout << "This program implements getTransaction" << endl; cout << "as a free (non-member) function"<< endl; causeApause(); char transaction; getTransaction(transaction); cout << endl << endl << "You entered '" << transaction << "'" << endl; } Execute with: p287 This program implements getTransaction as a free (non-member) function . . . Press Enter to continue . . . ATM ---------------------------------------- Withdraw [W] Deposit [D] Balance [B] Quit [Q] Select [W,D,B,Q]: B You entered 'B' Most repetition can be done with any of the three loop constructs but usually one will be better than the others If you know how many times you are going to loop use the for statement - if you do not know the number of repetitions but the loop must execute at least once to initialize certain objects use the do while construct If the test needs to be performed first before the code will make sense use the while statement Structured classes allow us to store several different objects within one object as with the bankAccount and ATM classes with name and PIN etc. Arrays are structured classes which provide for collections of several objects of the same type A generic declaration looks like: class-name array-name [ int-expression ]; float scores[92]; Which provides for up to 92 float type test scores bankAccount customer[200]; works just as well where each customer will have a name, PIN and balance dice::dice(unsigned seed) dice list[20]; dice::dice() { r=g=1; srand((unsigned)time(NULL)); } We can refer to individual items in the collection with scores[37] = 78; or x = 5*scores[37] + 12; cout << "Test number " << n << " is " << scores[ n ]; n must be between 0 and 91 for this to work int a2,a3,a4,a5,a6...,a12; switch ( x=mydie.toss()) { case 2: a2++; break; case 3... int a[11]; for(int x=0; x< 11; x++) a[x]=0; a[mydie.toss() - 2]++; count++; count = count + 1; a[mydie.toss() - 2] = a[mydie.toss() - 2] + 1; x=mydie.toss() - 2; a[x] = a[x] +1; int a[13]; If n is an integer then scores[n] can be used anyplace that a float can be used and we can call member functions for a bankAccount object such as: cout << customer[8].name( ) << endl; for ( int x=0,sum=0; x<92; x++) sum= sum + scores[x]; float average = sum/92.0; src/p301-303.cpp // This program is made up of the code from // pages 301 through 303 #include #include "ourstuff.h" // for decimals(cout, 2) #include // for setw(3) int main() { float floatArray[5]; floatArray[0] = 12.6; floatArray[1] = 5.7; floatArray[2] = floatArray[0] + floatArray[1]; // Store 18.3 cout << "To match book, enter these two float values: 9.99 15.0 " << endl; cin >> floatArray[3] >> floatArray[4]; int j; decimals(cout, 2); cout << "All 5 Elements of floatArray: " << endl; for(j = 0; j < 5; j++) cout << j << ':' << setw(6) << floatArray[j] << endl; // Let the first element be the largest float largest = floatArray[0]; // Now compare the other array elements for(j = 1; j < 5; j++) { if(floatArray[j] > largest) largest = floatArray[j]; } cout << "The largest floatArray element = " << largest; return 0; } p301-303 To match book, enter these two float values: 9.99 15.0 9.99 15.0 All 5 Elements of floatArray: 0: 12.60 1: 5.70 2: 18.30 3: 9.99 4: 15.00 The largest floatArray element = 18.30 float scores[92]; Note that scores[92] is not part of the array and that scores[92] = 37; // will not cause a compiler error but will alter some value in memory that should not be changed - which will most likely cause a problem in your program - check that you are within range src/p305-307.cpp // This program illustrates arrays of // programmer defined objects. #include #include "ouracct.h" // for class bankAccount #include "ourstuff.h" // added for decimals int main() { int j; // Declare bankAccount customer[3]; customer[0] = bankAccount("Hall", "1234", 100); customer[1] = bankAccount("Small", "4321", 0); customer[2] = bankAccount("Ewall","1082", 10000.00); cout << "Show the three elements of customer: " << endl; for(j = 0; j < 3; j ++) cout << "customer[" << j << "]: " << customer[j] << endl; cout << endl; for(j = 0; j < 3; j ++) cout << customer[j].name() << endl; cout << endl; float sum = 0.0; for(j = 0; j < 3; j++) sum = sum + customer[j].balance(); decimals(cout, 2); cout << "The total balance is: " << sum << endl; return 0; } int Old = 0, New = 1; customer[New].deposit( customer[Old].balance() ); p305-307 Show the three elements of customer: customer[0]: { bankAccount: HALL, 1234, 100.00 } customer[1]: { bankAccount: SMALL, 4321, 0.00 } customer[2]: { bankAccount: EWALL, 1082, 10000.00 } HALL SMALL EWALL The total balance is: 10100.00 The program on pages 308 and 309 shows how to read data from a file of bank accounts into an array of bank accounts as is maintained by an object of the bank class earlier - this code also checks the range on the index of the array to make sure we do not write beyond the memory set aside for our list of bank accounts in customer We also generate the number of customers in the process of reading them in from the data file src/p309.cpp // Initialize an array of bankAccount objects through // file input. The file stores sixteen (16) customers. // The first bankAccount object is stored in // customer[0] and the 16th is stored as customer[15]. #include // for class ifstream #include "ouracct.h" // for class bankAccount int main() { // PRE: The input file 'bank.dat' is in the proper // directory, has valid format, and has no extraneous // lines at the end // POST: An array of bankAccount objects and the // number of customers stored in the file bank.dat // are set ifstream inFile("bank.dat"); if(! inFile) cout << "**Error** The file 'bank.dat' was not opened" << endl; else { const int MAX_CUSTOMERS = 20; bankAccount customer[MAX_CUSTOMERS]; string name, PIN; float balance; int numberOfCustomers = 0; while( (numberOfCustomers > name >> PIN >> balance; // Go to next line or make eof true inFile.ignore(80, '\n'); customer[numberOfCustomers] = bankAccount(name, PIN, balance); numberOfCustomers++; } // Antibugging tip: It is good practice to verify // that an array is properly initialized! // The numberOfCustomers is very important as is // the data stored at each array element. So first // output numberOfCustomers. Then display # // each bankAccount object with cout <<. cout << "Number of customers on file: " << numberOfCustomers << endl; cout << endl; cout << " The customers" << endl; cout << "=================================" << endl; for(int j = 0; j < numberOfCustomers; j++) cout << j << ". " << customer[j] << endl; } // end else return 0; } p309 Number of customers on file: 20 The customers ================================= 0. { bankAccount: CUST0, 0000, 0.00 } 1. { bankAccount: YOURLASTNAME, ANY4, 111.11 } 2. { bankAccount: AUSTEN, 2222, 222.22 } 3. { bankAccount: CHELSEA, 3333, 333.33 } 4. { bankAccount: CUST4, 4444, 444.44 } 5. { bankAccount: CUST5, 5555, 555.55 } 6. { bankAccount: CUST6, 6666, 666.66 } 7. { bankAccount: CUST7, 7777, 777.77 } 8. { bankAccount: CUST8, 8888, 888.88 } 9. { bankAccount: CUST9, 9999, 999.99 } 10. { bankAccount: CUST10, 1010, 1010.10 } 11. { bankAccount: CUST11, 1111, 1111.11 } 12. { bankAccount: CUST12, 1212, 1212.12 } 13. { bankAccount: CUST13, 1313, 1313.13 } 14. { bankAccount: CUST14, 1414, 1414.14 } 15. { bankAccount: HALL, 1234, 100.00 } 16. { bankAccount: CUST16, 1010, 1010.10 } 17. { bankAccount: CUST17, 1111, 1111.11 } 18. { bankAccount: CUST18, 1212, 1212.12 } 19. { bankAccount: CUST19, 1313, 1313.13 } cat src/bank.dat Cust0 0000 000.00 YourLastName ANY4 111.11 Austen 2222 222.22 Chelsea 3333 333.33 Cust4 4444 444.44 Cust5 5555 555.55 Cust6 6666 666.66 Cust7 7777 777.77 Cust8 8888 888.88 Cust9 9999 999.99 Cust10 1010 1010.10 Cust11 1111 1111.11 Cust12 1212 1212.12 Cust13 1313 1313.13 Cust14 1414 1414.14 Hall 1234 100.00 Cust16 1010 1010.10 Cust17 1111 1111.11 Cust18 1212 1212.12 Cust19 1313 1313.13 Cust20 1010 1010.10 Cust21 1111 1111.11 Cust22 1212 1212.12 Cust23 1313 1313.13 Cust24 1414 1414.14