-
Notifications
You must be signed in to change notification settings - Fork 26
/
Copy pathExercise 12.3 (Completed)
553 lines (471 loc) · 17.2 KB
/
Exercise 12.3 (Completed)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
1. (Review) a. Explain how dynamic allocation of memory works.
dynamic allocation of memory, in which the amount of storage to be allocated is assigned, as requested, at runtime
instead of being fixed at compile time. Dynamic allocation of memory is useful when dealing
with lists and objects because it allows expanding the list as new items are added and contracting
the list as items are deleted.
b. Describe the process of creating a dynamically allocated object. Specifically, discuss the
roles of a pointer variable and the new operator in creating a dynamically allocated object.
After an object has been dynamically created, it can be accessed only by using the address
the new operator returns. So like the this pointer, the newly created object’s address must be
stored in a pointer variable
c. Discuss the importance of deleting dynamically allocated objects, and explain what can
happen if these objects aren’t deleted.
Deleting dynamically created objects when their usefulness ends is crucial. Otherwise, as new objects are created,
the computer starts to “eat up” available memory space, especially if the same pointer
is used in creating a new object before the old object is deleted. The reason is that after an
existing object’s address is overwritten with a new object’s address, there’s no way for the
system to reclaim the memory. This condition is referred to as memory leak.
2. (Review) a. Explain what a pointer is.
The variable that stores the address of another variable
b. For each of the following pointer declarations, identify the pointer variable’s name and
the data type of the object to be accessed when the address in the pointer variable is
dereferenced:
i. Checkout *a;
declares a as the pointer that can store the address
The data type of the object Checkout when dereferenced is a string.
ii. Pump *pointer1;
declares pointer1 as the pointer that can store the address
The data type of the object Pump when dereferenced is a string.
iii. Pump *addr_of_aPump;
declares addr_of_aPump as the pointer that can store the address
The data type of the object Pump when dereferenced is a string.
iv. int *addr_of_int;
declares addr_of_int as the pointer that can store the address
The data type of the object int when dereferenced is a interger.
v. double *b;
declares b as the pointer that can store the address
The data type of the object double when dereferenced is a double-precision interger.
c. If the asterisks were removed from the declarations in Exercise 2b, what would the names
before the semicolon represent?
The name would be a variable that stores a value and not an address.
3. (Practice) a. Enter and run Program 12.4, but specify the number of objects to be created as
four. Explain why your program outputs the same memory addresses.
#include "stdafx.h"
#include <iostream>
using namespace std;
// class declaration section
class Checkout
{
private:
int numItems;
double arrivalTime;
public:
Checkout(); // the constructor
// the following is an inline destructor
~Checkout()
{
cout << "!!!!This Customer object has been deleted !!!!\n";
};
void showObject();
void getItems(){ return; }; // inline do-nothing methods
void getTime() { return; }; // will be used in Program 12.5
};
// class implementation section
Checkout::Checkout() // constructor
{
cout << "\n**** A new Customer object has been created ****\n";
numItems = 5;
arrivalTime = 2.5;
}
void Checkout::showObject()
{
cout << " For this object:\n";
cout << " numItems = " << numItems
<< " arrivalTime = " << arrivalTime << endl;
return;
}
int main()
{
Checkout *anotherTrans; // pointer to a Checkout object
int i, howMany;
cout << "Enter the number of transactions to be created : ";
cin >> howMany;
for (i = 1; i <= howMany; i++)
{
anotherTrans = new Checkout; // create a new Checkout object
// display the address of the created object
cout << "The memory address of this object is : " << anotherTrans << endl;
anotherTrans->showObject(); // display contents of this object
delete anotherTrans; // delete the object
}
system("pause");
return 0;
}
// The address remains the same because the memory used is constatantly being deleted and reused.
b. Remove the statement delete anotherTrans; or convert it to a comment (called “commenting
out”), and rerun Program 12.4. Again, make sure to have the program create four
new objects. Explain why the memory addresses now differ for each new object.
The addresses memory locations storage is always allocated and never deleted.
c. Using the results of Exercise 3b, why is it no longer possible to access any of the first three
created objects after the fourth object has been dynamically created? What does this imply
about the previously allocated memory, and why is it a serious flaw in the program?
because they take up memory at run-time which mean that the memory is unchangeable within the code before hand.
This implies that previously allocated memory is non-reusable.
If the size of the program was to grow large enough there would be no memory slot to save result and the program would crash.
4. (Practice) Enter and run Program 12.5.
#include "stdafx.h"
#include <iostream>
#include <ctime>
#include <cmath>
using namespace std;
// Checkout class
// precondition:
// srand() must be called once before any member method
// post-conditions:
// getItems() returns an integer random no. of items between 1 and 20
// getTime() returns an arrival time between 0.0 and 3.0
// class declaration section
class Checkout
{
private:
// no class variables
public:
Checkout() { cout << "\n**** A new Customer has arrived ****\n"; };
~Checkout()
{
cout << "!!!!This Customer object has been deleted !!!!\n";
};
int getItems(){ return(1 + rand() % 15); };
double getTime(){ return((double(rand()) / RAND_MAX) * 3); };
};
int main()
{
Checkout *anotherTrans; // declare a pointer to a Checkout object
int i, howMany;
cout << "Enter the number of simulations to be created : ";
cin >> howMany;
srand(time(NULL));
for (i = 1; i <= howMany; i++)
{
// create a new Checkout object
anotherTrans = new Checkout;
// use the pointer to access the member methods
cout << "The arrival time is " << anotherTrans->getTime() << endl;
cout << "The number of items is " << anotherTrans->getItems() << endl;
// delete the object
delete anotherTrans;
}
system("pause");
return 0;
}
5. (Desk check) For the following class, determine what the two member methods accomplish:
#include <iostream>
#include <ctime>
#include <cmath>
using namespace std;
// Coin class
// precondition:
// srand() must be called once before the flip()method is called
// class declaration section
class Coin
{
private:
static int totalHeads;
static int totalTails;
public:
Coin() {cout << “\n**** A new Coin object has been created ****”;};
~Coin() {cout << “\n!!!! This Coin object has been deleted !!!!\n”;};
void flip();
static void percentages();
};
// static member definition
int Coin::totalHeads = 0;
int Coin::totalTails = 0;
// class implementation section
void Coin::flip()
{
if( double(rand())/RAND_MAX < 0.5)
{
++totalTails;
cout << “\nThe coin flip came up tails”;
}
else
{
++totalHeads;
cout << “\nThe coin flip came up heads”;
}
return;
}
void Coin::percentages() // this calculates the percentages of
{ // heads and tails and displays the result
int tosses = totalHeads + totalTails;
cout << “\nNumber of coin tosses: “ << tosses;
cout << “\n “ << totalHeads << “ Heads “
<< totalTails << “ Tails\n”;
cout << “\nHeads came up “ << 100.0 * double(totalHeads)/tosses
<< “ percent of the time.”;
cout << “\nTails came up “ << 100.0 * double(totalTails)/tosses
<< “ percent of the time.”;
return;
}
The two member methods accomplish the result of a coin tose and the percentage that the result of that tose came up heads or tails
6. (Program) a. Compile a program that uses the following main() function with the Coin class
given in Exercise 5:
int main()
{
Coin *anewCoin; // declare a pointer to a Coin object
int i, howMany;
cout << “Enter the number of flips: “;
cin >> howMany;
srand(time(NULL));
for(i = 1; i <= howMany; i++)
{
anewCoin = new Coin; // create a new Coin object
anewCoin->flip(); // flip the coin
delete anewCoin; // delete the object
}
Coin::percentages(); // call the static member method
return 0;
}
b. Run the program written for Exercise 6a so that it produces four flips of the coin.
Done!!
7. (Modify) a. Remove all the cout statements from the constructor, destructor, and flip()
methods in the Coin class given in Exercise 5. Then combine the modified class with the
main() function given in Exercise 6a to produce an executable program.
Done!!
b. Run the program written for Exercise 7a three times. On the first run, have your program
simulate flipping the coin 10 times; the second run, 100 times; and the third run, 1000 times.
Make sure each created object is deleted in the while loop.
Done!!
c. What problem can occur if each created object isn’t deleted in your program? Do you think
this problem is serious?
The program could use up all of it memory space causing the program to crash. Yes this is a serious problem if the program is required to cycle though a large number of flips.
8. (Modify) a. Modify the program written for Exercise 6a or 7a to contain a single dynamically
allocated Coin object. It should be created before the for loop is entered and deleted after
the loop completes its execution.
#include "stdafx.h"
#include <iostream>
#include <ctime>
#include <cmath>
using namespace std;
// Coin class
// precondition:
// srand() must be called once before the flip()method is called
// class declaration section
class Coin
{
private:
static int totalHeads;
static int totalTails;
public:
Coin() { cout << "\n**** A new Coin object has been created ****"; };
~Coin() { cout << "\n!!!!This Coin object has been deleted !!!!\n"; };
void flip();
static void percentages();
};
// static member definition
int Coin::totalHeads = 0;
int Coin::totalTails = 0;
// class implementation section
void Coin::flip()
{
if (double(rand()) / RAND_MAX < 0.5)
{
++totalTails;
cout << "\nThe coin flip came up tails";
}
else
{
++totalHeads;
cout << "\nThe coin flip came up heads";
}
return;
}
void Coin::percentages() // this calculates the percentages of
{ // heads and tails and displays the result
int tosses = totalHeads + totalTails;
cout << "\nNumber of coin tosses : " << tosses;
cout << "\n " << totalHeads << " Heads "
<< totalTails << " Tails\n";
cout << "\nHeads came up " << 100.0 * double(totalHeads) / tosses
<< " percent of the time.";
cout << "\nTails came up " << 100.0 * double(totalTails) / tosses
<< " percent of the time.";
return;
}
int main()
{
Coin *anewCoin; // declare a pointer to a Coin object
int i, howMany;
cout << "Enter the number of flips : ";
cin >> howMany;
srand(time(NULL));
anewCoin = new Coin; // create a new Coin object
for (i = 1; i <= howMany; i++)
{
anewCoin->flip(); // flip the coin
}
delete anewCoin; // delete the object
Coin::percentages(); // call the static member method
system("PAUSE");
return 0;
}
b. Discuss the advantages and disadvantages of using multiple Coin objects compared with
creating a single Coin object.
By using multiple Coin objects your results are more controlled and the results are somewhat predetermined.
By using one Coin object your result are more random and realistic because the result isn't know until the run time.
c. Is using a dynamically created object for the program written for Exercise 7a necessary?
No, the program will produce decent result without dynamically creating the object.
9. (Program) a. Write a program that simulates a customer’s arrival at a gas station and the
amount of gas requested. Each customer should arrive randomly between 1 and 15 minutes
and request between 3 and 15 gallons of gas. The name of your class should be Customer.
#include "stdafx.h"
#include <iostream>
#include <ctime>
#include <cmath>
using namespace std;
// Customer class
// precondition:
// srand() must be called once before the flip()method is called
// class declaration section
class Customer
{
private:
//none
public:
Customer() { cout << "\n**** A new Customer object has been created ****"; };
~Customer() { cout << "\n!!!!This Customer object has been deleted !!!!\n"; };
void arrgas();
static void total_gas();
};
// class implementation section
void Customer::arrgas()
{
int arrival, gas, total;
arrival = rand() % 15 + 1;
cout << "Arrival Times " << arrival << endl;
gas = rand() % 15 + 3;
cout << "Gas Requested " << gas << endl;
return;
}
int main()
{
Customer *anewCustomer; // declare a pointer to a Customer object
anewCustomer = new Customer; // create a new Customer object
anewCustomer->arrgas(); // flip the Customer
delete anewCustomer; // delete the object
system("PAUSE");
return 0;
}
b. Include the class written for Exercise 9a in a program that simulates the arrival of 10 customers
(using a while loop). The arrival time and number of gallons of gas each customer
requests should be displayed. After the last customer, your program should display the total
number of gallons requested.
#include "stdafx.h"
#include <iostream>
#include <ctime>
#include <cmath>
using namespace std;
// Customer class
// precondition:
// srand() must be called once before the flip()method is called
// class declaration section
class Customer
{
private:
//none
public:
Customer() { cout << "\n**** A new Customer object has been created ****" << endl; };
~Customer() { cout << "\n!!!!This Customer object has been deleted !!!!\n"<< endl; };
void arrgas();
};
// class implementation section
void Customer::arrgas()
{
int arrival, gas, total = 0, number = 0;
while (number <= 10){
arrival = rand() % 15 + 1;
cout << "Arrival Times " << arrival << endl;
gas = rand() % 15 + 3;
cout << "Gas Requested " << gas << endl;
total = +total + gas;
if (number < 10){
cout << "Next Customer!!" << endl;
}
number++;
}
cout << "The total amount of gas bought was " << total << endl;
return;
}
int main()
{
Customer *anewCustomer; // declare a pointer to a Customer object
anewCustomer = new Customer; // create a new Customer object
anewCustomer->arrgas(); // flip the Customer
delete anewCustomer; // delete the object
system("PAUSE");
return 0;
}
10. (Modify) a. Modify the class written for Exercise 9a to include the grade of gas. Assume there
are three grades of gas: 87 octane, 93 octane, and 97 octane.
Done!!
b. Include the class written for Exercise 10a in a program that simulates the arrival of 10 customers
(using a while loop). The arrival time, number of gallons of gas each customer
requests, and octane rating of the gas should be displayed. After the last customer, your
program should display the total number of gallons requested for each grade of gas.
#include "stdafx.h"
#include <iostream>
#include <ctime>
#include <cmath>
using namespace std;
// Customer class
// precondition:
// srand() must be called once before the flip()method is called
// class declaration section
class Customer
{
private:
//none
public:
Customer() { cout << "\n**** A new Customer object has been created ****" << endl; };
~Customer() { cout << "\n!!!!This Customer object has been deleted !!!!\n"<< endl; };
void arrgas();
};
// class implementation section
void Customer::arrgas()
{
int arrival, gas,gas1 = 0,gas2 = 0,gas3 = 0, gas_grade, total = 0, number = 0;
while (number <= 10){
arrival = rand() % 15 + 1;
cout << "Arrival Times " << arrival << endl;
gas = rand() % 15 + 3;
if (gas >= 3 && gas <= 8){
gas_grade = 87;
gas1 =+ gas1 + gas;
}
if (gas >= 9 && gas <= 11){
gas_grade = 93;
gas2 =+ gas2 + gas;
}
if (gas >= 12 && gas <= 15){
gas_grade = 97;
gas3 =+ gas3 + gas;
}
cout << "Gas Requested " << gas << " gallons of grade " << gas_grade << endl;
total = +total + gas;
if (number < 10){
cout << "Next Customer!!" << endl;
}
number++;
}
cout << "The total amount of gas bought was " << total << endl;
cout << "The total at grade 87 was " << gas1 << endl;
cout << "The total at grade 93 was " << gas2 << endl;
cout << "The total at grade 97 was " << gas3 << endl;
return;
}
int main()
{
Customer *anewCustomer; // declare a pointer to a Customer object
anewCustomer = new Customer; // create a new Customer object
anewCustomer->arrgas(); // flip the Customer
delete anewCustomer; // delete the object
system("PAUSE");
return 0;
}
c. What does your simulation assume about the comparative desirability of each grade of gas?
Is this assumption realistic?
My simulation assumes that the 97 grade had the most gallons bought. The assumption is random and therefore realistic.
d. Based on your answer to Exercise 10c, what are the implications of using the simulation to
determine how much of each grade of gas to supply to a gas station?
A random selection of gas is not a valid database of customer habits. Therefore using this simulation in real life would be careless and costly.