Вы находитесь на странице: 1из 782

WALTER SAVITCH

PROBLEM SOLVING
:viai THE OBJECT
OF PROGRAMMING

Fourth Edition

Addison-Wesley
Boston San Francisco New York
London Toronto Sydney Tokyo Singapore Madrid
Mexico City Munich Paris Cape Town Hong Kong Montreal

4-

- - - -
-- - - -
- -
2004
32.973-018.1
681.3.06
13

13 C++. 4- . / . . .: ; :
BHV, 2004. 781 : .
ISBN 5-94723-582-
C++.
, , , , ,
., ,
, , .
, ,
.
,
C++.

32.973-018.1
681.3.06

Addison-Wesley Longman.
.
.
, , , .
, ,
, .

2003 by Pearson Education, Inc.


ISBN 0321113470 (.) , 2004
ISBN 5-94723-582- , , 2004

17
1. C++ 19
2. C++ 50
3. 106
4. 156
5. - 192
6. 254
7. .310
8. 370
9. 416
10. 447
11. 515
12. 558
13. 598
14. 633
15. 656
16. 683
17. 725
749
768

17
17
18
.. 18
18

1 . C++ 19
1.1. 19
19
24
25
26
28
1.2. 29
29
30
- 32
33
1.3. C++ 34
C++ 34
C++ 35
: / \ 38
: 38
C++ 39
: Include 41
C++ 41
: 41
1.4. 43
44
: , 45

45
46
48

2. C++ 50
2.1. 50
50
52
54
55
: 56
: 58
2.2. - 58
cout 59
Include 60
61
:
63
63
cin 64
66
: - 66
2.3. 67
int double 67
69
char .70
bool 72
72
73
: 75
77
2.4. 77
78
: 83
: = == 83
84
86
90
: 90
: 92
2.5. 93
94
94
96
8

98
99
103

3. 106
3.1. 106
3.2. 107
107
111
113
: 113
3.3. , 114
115
120
: 120
122
123
3.4. 124
124
: 126
: 126
: 132
3.5. 133
133
: 135
135
, ,
137
std 139
: , 141
3.6. 142
143
: 145
147
149
150
153

4. 156
4.1. void 156
void 157
: 158
return void 160

4.2. 162
162
165
: swap_values 167
168
: ....169
: ,
170
4.3. 173
, 173
173
: 176
4.4. 180
180
185
185
188
5. - 192
5.1. - 192
- 193
- 194
197
: , 199
- 201
( ) 204

( ) 205
5.2. - 208
208
211
214
: 216
217
: 218
5.3. - 219
- get put 220
- putback ( ) 222
: 224
: \ 225
- eof 228
: 230
232
: toupper tolower int 234
1

5.4. 235
236
: newjine 239
,
( ) 240
242
243
249
6. 254
6.1. 254
254
: 258
259
: 260
261
6.2. 264
- 264
269
: - 274
: 275
: ....277
: BankAccount 278
: 282
284
: ,
289
: 291
6.3. 293
293
: BankAccount 296
301
301
307
7. 310
7.1. 310
310
: int 314
, 316
( ) 317
7.2. 318
if...else 318
: 319
11

if...else 321
: 323
switch 326
: break switch 329
switch 329
:
331
331
: , 334
7.3. C++ 335
while 335
337
for 340
: for 344
344
: 346
break 347
: break 348
7.4. 349
349
350
353
357
359
360
366
8. 370
8.1. 370
: 370
373
: ,
376
: -, 378
: Money 379
digit_toJnt ( ) 384
: 385
const 387
: const 388
8.2. 391
392
395
396
398
12

406
406
413

9. 416
9.1. 416
417
: DigitalTime 418
#ifnclef 427
: 429
9.2. 430
using 430
432
434

( ) 435
436
: 441
: 441
443
443
445
10. 447
10.1. 447
447
: for 449
: 450
:
450
450
: 452
453
10.2. 455
455
457
const 460
: const 462
, 1 463
: 463
10.3. 475
475
:
478
: 479
: 481
13

10.4. 485
485
489
: 489
10.5. 493
493
494
: , 495
: 499
499
500
506

1 1 . 515
11.1. 515
516
: = == 519
cstring 521
524
527
11.2. string 532
string 532
- string 534
: getline 537
: cin
getline 538
string 539
: 542
string 546
11.3. 547
547
: 550
:
550
550
552
552
554

12. 558
12.1. 558
- 559
565
: 566
14

566
: 566
12.2. 568
- 569
570
( ) 574
( ) 576
12.3. 578
: 578
582
: , 584
585
590
592
593
595
13. 598
13.1. , 11 599
: 599
604
: 605
607
: 609
609
13.2. , 610
, 610
: 611
13.3. 615
615
: 616
: - 623
626
627
630
14. 633
14.1. 633
634
: 637
: 639
: 643
: 643
14.2. 644
644
: - 647
15

650
651
654

15. 656
15.1. 656
656
661
662
: 664
665
668
669
:
672
15.2. 673
673
: Stack 674
678
678
680
16. 683
16.1. 683
684
691
: - ....693
: - 694
protected 695
- 697
700
700
16.2. 701
, 702

702
. 703
16.3. 705
705
C++ 706
711
: 714
: - .714
:
- 715
: 716
16

717
718
722

17. 725
17.1. 726
. 726
733
735
: 737
: 738
738
740
: 741
17.2. 742
743
: 744
: try...catch 744
: 744
745
745
746
746
746
747

1. C++ 749

2. 750

3. ASCII 752

4. 753

5. assert 759

6. 760

7. 761

8. this 763

9. - 766

768

++
. -
,
. ,
.
,
.
. ,
,
, ,
.
ANSI/ISO
, C++.


C++
. :

.
, C++.
.

,
. ,
, . ,
,
, . ,

.
, , C++,
- .
18


,
. , ,
.

, .
, , ,
, , ,
, .
, .
- ,
C++.
, .
, ,
- (
).

,
, .
,
.
,
, .
,

. .
, ,
, .


,
http://www.aw.com/savitch/,
http://www-cse.ucsd.edu/users/savitch/.


, ,
comp@piter.com ( , ).
!

BHV - http://www.piter.com http://www.bhv.kiev.ua.
1


C++

...
.
(1792-1871)

,
.
C++ , .

1.1.
, , ,

. ,
, . ,
,
.
,
. , ,
,
. ,
.


: ,
. ()
20 1. C++

,
. ,
, .
, , ,
;
.
, ,
,
.
,
(,
).
, .
, ,
. ,
.
,
. 1.1.
: ( ) , (
) , (
), . , ,
, .
,
.
. . 1.1
.
,
.
.
,
. , /-
. .
,
.
,
.

.
. : (
) .
, .
,
;
, .
1.1. 21

.

. ,
,
.
, ,
( , ).
8 .

. , ; ,
. , ,
, .

()


() ()

. 1 . 1 .

,
(, ),
.
, ,
. ,
,
, .
. 1.2 .

.
22 1. ++

3- 1

2- 4
1- 6

3- 7

. 1.2.


, .
.
, ,
. ,
, .

,
, C++ (
).
. ,
, .
.
:
, - , , - . .
,
01000001 , 65. ,
,
, ,
. ,
, ,
, .
,
.
, .
1.1. 23

,
, (
.) ,
( )
,
.
,
,
, . ,
, ,
.
: , , .

.
, -. ( .)
- (CD)
-.
( ,
) (
).
-.
, . -
.
, ,
.
,
, ,
.


. ?
. -, 8 2 (8 2^).
, ,
2 10. -,
( , )
, .

{
) RAM ( . random access memory
).
.
,

.
24 1. C++

, ^ (),
. , ,
, , .
( ).
.
, , ,
. :
, 37,
59, 42
, , ,
1298. , , ,
, ,
.
,
.
.
, , .


,
.
. ,
.
.
- ,
, ,
. ,
, .
,
.
UNIX, DOS, Linux, Windows, Macintosh VMS.
,
. . 1.3,
: .
. ,
. ,
, . :
,
(
).
, , ,
. ,
, ~
. ,
.
1.1. 25

j ( j

. 1.3.


.
C++,
, (, Java, Pascal, Visual Basic, FORTRAN,
COBOL, Lisp, Scheme Ada).
. ,
.
,
.
, ,
. ,
.
:
ADD X Y Z

: , ,
X, , , Y,
, Z.
.
, ,
.
,
. , ADD ,
X 1001,YB I O I O H Z B 1001. ^
:
1001 1010 1001

, ,
.

, ( ).
( , ,
26 1. C++

), .
,
C++. ,
() ,
.

, , C++,
, .
,
, .

, , ,
.
,
. ,
, C++.
, .
C++.
,
. ,
,
. ,
, C++. ,
,
C++. . 1.4.
,
, :
C++,
.


, ,
, C++,
, .

C++
, . 1.4. C++
(, ),
, . ,
,
,
.
, .
1.1. 27

.
, . 1.5.
.


C++ C++


C++ J

. 1.4. C++ ( )

f C++

. 1.5. C++
28 1. C++


C++
(, ).
, .
.


1. .
2. , ?
3. ,
?
4.
?
5. ?
6. ? ?
7. ?
8. ?
9. ,
?
10. ?
. , :
.



, .
, 1822
. ,
. ,
,
, ,
. , .
,
, .
, , ,
, . ,
. ,
.
.
1.2. 29

1.2.

.
,
. ;
.
, .
, (1815-1852)


. C++,
.

,

. .
. ,
, C++ , - ,
, .
,

, , .

. , , , .

. ,
C++. ,
, ,
. ,
, ,
, ,
. , .
, .
.
,
.
,
.
, 1 5,
. , ,
, .
30 1. C++


,
, 4 .

, ,

1. .
2. ^ .
3. .
4.
.
5. , .

.
-, VIII-IX . -
, -
-,
. - ()
. -
, .

.
, ,
(, ) .
,
.


,
.


.
; , - ,
.
, . 1.6. ,
:
.
, .
, C++, .
.
1.2. 31

, ,
, .
,
, .
,
, .
, ,
, , :
, , .
, :
, , - .

J

- 1 "
^

^f
-^ ++

\ \

. 1.6.

- ,
,
,
. ,
? , !
, , , , ,
.
, ,
,
.

.
32 1. C++

. 1.6, .
, ,
.

,
. C++
.
,
, .
. 1.6 .
, ,
.
, ,
, .
, .
,
.

-

( ),
. ,
.
, - .
-
.
, - . , ,
,
. ,
. -
.
, . 1.6,
.
,
.
. , ,
, .

.
. -
, , ,
, .
' ,
. C++
1.2. 33

- ,
,
.


,
,
,
.
1. .
2. (
).
3. ( ).
4. .
5. .
6. .
,
,
. .
, ,
, , .
,
, .
, :
,
.


12. ,
, .
:
) ;
) ;
) ;
) , ;
) ;
) ;
) ;
) .
34 1. C++

13. ,
.
14. .
?
15. , .

1.3. C++
...
(1709-1784)

C++, .

++
, C++, .
? ? - -?
? .
, . ,
, , BCPL.
, C++, , . C++
? , ++ -
, C++,
. BCPL
. C++ .
1970- AT&T
Bell Laboratories. UNIX. (
,
, , ,
UNIX.) ,
,
UNIX. - UNIX,
. ,
,
, ; UNIX, .
,
.
, UNIX.
.
, , ,
. , ,
,
. ,
,
1.3. C++ 35

, ,
, ,
. ,
,
, . ,

.
1980- -
AT&T Bell Laboratories C++.
, , ,
C++. ( : C++
.) , C++
-
, .

C++
1.1 C++ ,
.
, ,
{ , ).
,
. , , .

. ,
, .
, , , .
C++,
, 1.1.
, ,
C++. , .
1.1. C++
#1nclude <1ostream>
using namespace std;

int mainO
{
1nt number_of_pods. peas_per_pod. total_peas;
cout "Press Enter after entering a number.\n":
cout "Enter the number of pods:\n";
cin number_of_pods;
cout "Enter the number of peas in a pod:\n";
cin peas_per_pod;

total_peas = number_of_pods * peas_per_pod;

cout "If you have ":


cout number_of_pods; ^
36 1. C++

1.1 {)
cout " pea pods\n";
cout "and ":
cout peas_per_pod;
cout " peas in each pod. thenVn";
cout "you have ";
cout total_peas;
cout " peas in all the podsAn";

return 0;
}

-Press Enter after entering a number.
Enter the number of pods:
10
Enter the number of peas in a pod:
9
If you have 10 pea pods
and 9 peas in each pod. then
you have 90 peas in all the pods.
,
. :
#include <iostream>
using namespace std;

int mainO
{
, : .
:
return 0;
}
: .
, ,
. ,
int number_of_pods. peas_per_pod. total_peas;
. ,
number_of__pods, peas_per_pod total_peas
. , ,
, :
. i nt (
. integer ), ,
, , ,
(, 1, 2, - 1 , -7, , 205, -103 . .).
,
- .
.
.
.
1.3. C++ 37

1 cout.
. 1 ( -)
. , ,
, , .
cout ( -) ,
. ,
, C++. ,
,
. '
,
. :
cout "Press Enter after entering a number.\n";

: "Press Enter after entering a number.\n" cout


"Press Enter after entering a number An". ,
cout ( ),
. \

, .
cout; :
Enter the number of pods:
, 1 , :
cin number_of_pods;
: number_of_pods cin
number_of_pods.
, cin (
), ,
numberofpods. ,
1.1. 10.
( ) ,
. Enter ( Return)
. , cin,
10 number_of_pods.
numberofpods 10;
, 10.
:
cout "Enter the number of peas in a pod:\n";
cin peas_per_pod;
.
. Enter,
peasperpod.
9. Enter
peasperpod 9.
38 1. C++

, :
total_peas = number_of_pods * peds_per_pod;
(*) C++ .
, numberofpods peasperpod. 10
9 90. (
, ): , ,
, . total peas
90.

- . :
cout "If you have ";
cout number_of_pods;
cout " pea pods\n":
, 1; , -
1 , cout.
, number_of_pods.
.
10. (,
numberofpods 10.) ,
:
If you have 10 pea pods
, .
,
\.
,
, .

: / \

, cout, \
: .
\, /,
, , .

:
1 , , cout
, , ,
,
. :
cin number_of_pods;
1.3. C++ 39

number_of_pods
cin .

cout number_of_pocls;

number_of_pods
cout.

C++
C++ 1.2.

, , ,
.
, .
, .

. ,

.
1.1 ,
1 nt. , ,
. , ,
, , (
1.1 1.2), .
, . 1.1
cout 1 , ,
total_peas, .

. ,
. ,
: .
1.2. C++
finclude <iostream>
using namespace std:

int mainO
{
_

J.
_2

return 0;
40 1. -+-+


. - .
#include <iostream>
include. ,
.
iostream , ,
; ,
. -
iostream
. iostream , ,
.
,
i ncl ude .
, .
#. ,
,
include.
include:
using namespace std:
, , iostream,
(std . standard ).
, .
,
:
int mainO
{
, ,
3. { }
.
, ,
.

return 0;
, .
, -
. ,
. ,
, return ,
.
,
, .
, .
. .
1.3. C++ 41

return ,
}.

:
include
, < (
lostream), >
(. 1.2). include
, !
, ,
. ,
, ,
, .

++
, ,
C++, 1.1.
?
C++ ,
, ,
. , ,
. ,
, , ,
.

, ,
, C++.
, .

, ,
() (,
). , ,
, .
.

. , .
, , .

:

C++ .
, . 1.3 (
42 1. C++

). .
, ,
. ,
.
1.3. C++
linclude <iostream>
using namespace std;

int mainO
{
cout "Testing 1. 2, 3\n":
return 0;
}

Testing 1. 2. 3

, .
. -
, .
, , ,
Testing 1. 2, 3
, , .
return ; :
char l e t t e r ;
cout "Enter a l e t t e r to end the program:\n";
cin l e t t e r ;
, .
:
cout "Testing 1, 2. 3\n";
char letter;
cout "Enter a l e t t e r to end the program:\n":
cin l e t t e r ;
return 0;
, 2.
,

#include <iostream>
.h, :
#include <iostream.h>
,
using namespace std;
iostream.h iostream, ,
C++,
.
1.4. 43

,
C++,
- - .
, ,
C++. ,
, .


16. C++
cout "C++ is easy to understand.";
OH .
?
17. \ (. 1.1):
cout "Enter the number of peas in a pod:\n":
18. (. 1.1):
1 peas_per_pod;
19. (. 1.1):
total_peas = number_of_pods * peas_per_pod:
20.
#1nclude <1ostream>
21. ( - )
include:
) #include <iostream >
) linclude < iostream>
) #include <iostream>

1.4.
?
, .
- .
-, , .

.
, , debugging,
,
, bug ( ), 1; , , ,
. - -
(1906-1992)
44 1. ++

.
Harvard Mark I,
, .
:
.
- , .
. , ,
, , , ;-
- debugging.
.

, .



1;. ,
, (
) , .
,
, , . ,
, ,
. , ,
, ,
. ,
. ,
.
,
, .
, , -,
,
. :
, ?
,
, .
,
.
.
.
. ,
,
.
,
, , . ,
,
45

, , , .
C++
. , 1.1
+ *, .
;, .
,
, , .
,
, . ,

. , ?

: ,

,
, .
, , ,
:
- . ,
.


22. .
23. ?
24. (, ) .
?
25. (}),
. ?
26. , ,
. ?
? ?
27. , ,
, ,
, .
?


. ,
, .
46 1. C++

: ()
, () , (),
.
: .
.
, .
,
. .
, .
.
,
, . .
, ,
, ,
.
.
(, )
(, C++).
.
C++,
( ).
: , -
.
, .
C++ .
C++
. ( .)
C++, cout ,
, , 1 , .



1. : ,
, (), .
2. .
3. .
4. ,
.
, .

() .
47

5.
.
6. ,
, .
, ,
.
7.
,
, .
8.
.
9. Macintosh, Windows 2000, Windows , VMS, Solaris, SunOS,
UNIX ( UNIX-, Linux).
.
10. C++
(,
). .
.
. .
UNIX- ,

Windows Macintosh.
12. ), ), ), ) ,
. ,
, ,
, .
.
13. , , ,
, , .
14. .
15. , , ,
.
16. C++ 1s easy to understand
17. \
, .
18. ,
, peasperpod.
19. num-
ber_of_pods peas_per_pod total_peas.
20. #1nclude <1ostream> 1os-
tream. 1, cout ( )
( ) , .
48 1. C++

iostream
-.
21. ) Iostream ];
;
) Iostream
;
) .
22. : ,
.
23. .
, . .
24. .
25. .
26. ,
, ,
.
27. .


1. C++, 1.1,
. ,
, .
#.
. ,
. ,
.
.
2. C++, 1.
, Hello,
, ,
1.1.
. .
,
Good-bye.
\, :
cout "Good-bye\n";
(
\, .)
.
49

3. C++ 1 2.
* +.
. ,
,
, . ,
.
4. C++,
. ,
1.1, . ,
,
1.1. ,
#. ,
\. ,
, :
cout "This is the end of the program.\n":
(
\, .)
5. ,
,
. ,
,
.

1-4.
:
, , ,
, ( ,
) . ,
,
.
,
:
) < iostream;
) < > include;
) int int main ;
) main;
) int main ;
) ,
cout, ci n, <
cout, . .
2
C++

,
, .
, .

C++,
, .

2 . 1 .

, , ,
.

, .
C++
, .
, , C++,
. ,
2.1, .
, .

, .

C++ .
. -
, . ,
2.1. 51

, C++
. ,
, - (
,
). , ,
. 2.1
: number_of_bars, one_we1ght total_we1ght.
, (. 2.1),
number_of_bars
1 number_of_bars;

.

12. , .
2 . 1 . C++
#1nclude <1ostream>
using namespace std;
int malnO
{
int number_of_bars;
double one_weight, total_weight;
cout "Enter the number of candy bars in a package\n";
cout "and the weight in ounces of one candy bar.\n";
cout "Then press Enter.\n":
cin number_of_bars:
cin one_weight;

total_weight = one_weight * number_of_bars;

cout number_of_bars " candy bars\n":


cout one_weight " ounces eachVn";
cout "Total weight is " total_weight
" ounces.\n":

cout "Try another brand.\n";


cout "Enter the number of candy bars in a packageVn";
cout "and the weight in ounces of one candy bar.\n";
cout "Then press Enter.\n";
cin number_of_bars;
cin one_weight:

total_weight = one_weight * number_of_bars:

cout number_of_bars " candy bars\n";


cout one_weight " ounces each\n":
cout "Total weight is " total_weight
" ounces.\n";

cout "Perhaps an apple would be healthier.\n";


return 0;
52 2. C++


Enter the number of candy bars in a package
and the weight in ounces of one candy bar.
Then press Enter.
11 2.1
11 candy bars
2.1 ounces each
Total weight is 23.1 ounces.
Try another brand.
Enter the number of candy bars in a package
and the weight in ounces of one candy bar.
Then press Enter.
12 1.8
12 candy bars
1.8 ounces each
Total weight is 21.6 ounces.
Perhaps an apple would be healthier.
, .

,
( 1).
,
. ,
1001, 1003 1007.
,
. ,
, . ,
.

,
, +-+- ,
, :
1.3 1.
C++ .


, , ,
,
.
. (
) .
,
, ,
. ,
X, 1, _1, _, ABC123Z7, sum, RATE, count, data2, B1g_Bonus
2.1. 53

, ,

.
.
12, , ^change, data-l, myfirst.c, PROG.CPP
,
, , ,
.
C++ ,
, .
C++
:
rate, RATE, Rate
,
. C++
, .
, main, 1 cout,
. ,
, .
C++ ,
, ,
.


C++ ,
.
, ,
, .

,
. C++
-
. 1.
, ,
C++, . , ,
1 cout? ,
, .
, ,
C++. ,
. ,
, ,
,
54 2. C++

.
, .


C++ .
, , ,
. ,
2.1 :
1nt number_of_bars:
double one_we1ght. total_we1ght:
,
. ,
.
1 nt, , . integer -
. , C++
. , number_of_bars
1 nt,
, 1, 2, - 1 , , 37 -288.
- onewelght total _weight
double.
, , 1,75 -0,55.
, , 1 nt
doubl , .


.

_ __1, __2, . . . ;

1nt count. number_of_dragons. number_of_trolls;
double distance:

, C++,
.
,

int mainO
{
, .
,
. ,
2.1. 55

, ,
.

. ,
. .
( , ),

.


, ,
. , ,
.
,
, , .



. ,
.
2.1:
total_we1ght = one_weight * number_of_bars;
, total weight
, oneweight,
numberofba rs. ( 1 , * C++
.)

: , , ,
. ,
, , ,
(, * +).

, . ,
, .

. , :
total_we1ght = one_we1ght + number_of_bars;

, , ,
, total weight
oneweight numberofbars. ,
2.1, ,
, .
56 2. C++


.
total_we1ght = one_we1ght;
total weight oneweight.
,
( ),
.
- , number_of_bars
37:
number_of_bars = 37:
, 37 ,
,
.
,
. :
number_of_bars = number_of_bars + 3;
,
, numberofbars
. :
nuniber_of_bars
. C++ , .



, ,
.

= :

distance = rate * time;
count = count + 2;

:
,
. , minimumnumber
(, cin)
, :
des1red_n umber = m1n1murn_number + 10;

mi nimumn umber ,
. ,
, , ,
2.1. 57

. , ,
.
, ];
, .
, ,
. :

, ,
.

.
,
:
int m1n1mum_number = 3;
m1n1mum_number 1nt
3. ,

, . , ;
, : ,
. ,
:
double rate = 0.07. time, balance = 0.0;
C++
. ,
double rate(0.07). time. balance(O.O);
.
,
, .


, ,
.

_ __1 = _1,
__2 = _2. . . . ;

int count = 0. l i m i t = 10. fudge_factor = 2;
double distance = 999.99;

_ __1(_1).
__2{_2), . . . ;

intcount(O). l i m i t ( l O ) . fudge_factor(2):
double distance(999.99);
58 2. C++

:

, ,
.
. :
X = * z;

distance = speed * time:


,
, -
, :
, .

1. feet inches.
1 nt .
,
.
2. count distance.
count int ,
distance double 1,5.
3. , sum
1 2, int.
4. , length double
8,3.
5. , product ,
. i nt.
6. , ,
, , .
. , .
7. :
) ;
) ;
) .

2.2. -
.

C++
. -.
2.2. - 59

,
. ,
.
, . ,
, 5,
, ,
.
. ,
, 5 ,
.

cout
C++
cout (
).
,. 2.1:
cout number_of__bars " candy barsXn";
:
number_of_bars candy bars,
( \).
, cout .
, ,
. <
.. , ,
. , cout,
.
:
cout numbGr_of_bars;
cout " candy barsXn":
cout,
, :
cout " The total cost is $" (price + tax);
price tax .

, .
, cout,
. ,
2.1:
cout number_of_bars " candy bars\n";
cout one_weight " ounces each\n";
:
cout number_of_bars " candy barsXn" one_weight
" ounces eachXn";
60 2. C++

.
, ,
, cout, .
:
cout number_of_bars " candy bars\n"
one_weight " ounces eachXn";

,
,
.
, ,
. , ,
cout, ()
, .
.
, ,
( ),
. ,
: ,
.
. ,
, cout,
.
/ ,
.
,
: , ,
:
cout f1rst_number " " seconcl_number;

1, \
. ,
.
, , ,
, . C++
,
\ ( ),
. ,
, .

include
:
#1nclude <1ostream>
using namespace std;
2.2. - 61

include.
lostream,
1 cout.
lostream,
.
. C++
. ,
1 cout.
using namespace std;
using. ,
std ( . standard ),
,
. ci cout
iostream, , std.
,
std.
.
? , C++
,
, ,
.
, C++ ,
.
, .
C++, ,
. C++ (
),
().
,
? , ,
, .
C++ i ncl ude:
llnclude <iostream.h>
,
#1 nclude <iostream>
using namespace std:
.
, , C++,
.


(\) ,
, .
62 2. C++

. ,
\, , C++
.
\ " (
), .
,
, , ,
~
, .
, -
1 , -
. , \z,
z, .
ANSI , ,
, . ,
, . ,
, ,
.
:
\
\t
\
\\
\"
,
:
cout " \ " :

endl,
"\":
cout endl;

\ endl , -. \
, endl .
\ endl:
, ,
\:
cout "Fuel efficiency is "
mpg " mi lies per gallonXn":

,
endl:
cout "You entered "
number endl:
2.2. - 63


, ,
, \:
cout "You have d e f i n i t e l y won\n"
" one of the following p r i z e s : \ n " :
, \n .
endl.
, :
cout "You have d e f i n i t e l y won" endl
" one of the following prizes:" endl:

:

:
.
, \, ,
endl.
. ,
,
. ,

, .
.


doubl ,
, . ,
cout "The price is $" price endl;
.
price 78.5, :
The price is $78.500000
:
The price is $78.5
( 2.3):
The price is $7.85000001
, :
The price is $78.50
, .
,
, , .
64 2. C++

, ,
, (, double),
. ,
, :
cout. setfdos:: fixed);
cout.setf(10S::showpoi nt);
cout.precision(2):
,
, cout, doubl
. ,
cout " $" price endl:
, price
78.5. :
$78.50

2
i nt.
,
, 5.
, , ,
.
,
-,
, .
.
,
cout.precision(5):

5
double.

double
:
cout.setf(ios::fixed);
cout.setf(iOS::showpoint):
cout.precision(2):

double ( , )
. 2
int.

cin
cin
cout. ,
2.2. - 65

cout , 1 . ,
2.1 number_of_bars one_we1ght
> , 1 (
, ):
cout "Enter the number of candy bars in a package\n";
cout "and the weight in ounces of one candy bar.\n":
cout "Then press Enter.\n":
cin number_of_bars;
cin one_weight;
cin
. ,
cout "Enter the number of candy bars in a packageXn";
cout << "and the weight in ounces of one candy bar.\n";
cout "Then press Enter.\n":
cin number_of_bars one_weight;
.
cin :
cin number_of_bars
one_weight;
, cout,
ci .
, ci ,
,
,
. . ,
Enter,
, .

. , , 12 5
, 125.
cin,
,
. ,
, , .

cin
cin
, .

cin _1 _2. ...;

cin number size:
cin time_to_go
points_needecl;
66 2. C++


, , , - ,
,
.
cin
( ,
).
, .
:
cout "Enter the number of candy bars in a packageXn";
cout "and the weight in ounces of one candy ";
cout "Then press Enter.\n":

.
, .
, .

, , .
-. ,
, ; ,
. :
. -
.

:
-
,
.
, ,
\ end!. :
cout "Enter cost per person: $";
cin cost_per_person:

-
:
Enter cost per person: $

, :
Enter cost per person: $1.25


8. , :
The answer to the question of
Life, the Universe, and Everything is 42.
2.3. 67

9. , thenumber ( 1nt)
. ,
.
10. , double
?
. C++, Hel 1
word. .
12. C++,
. ,
- , .
13. , .
14. ,
double one, two, three, four, five 1.0,1.414,
1.732, 2.0, 2.236. ,
.
\t. ,
, .
.
,
.
, .
:
N Square Root
1 1.000
2 1.414
3 1.732
4 2.000
5 2.236

2.3.
. .

int double
2 2.0 . C++
. 2 1 nt,
2.0 double,
, .


. C++ ,
68 2. C++

1 nt . doubl .
,
. double
, 14
. ,
. , ,
,
int.
double , int.
,
double .
,
. :
, C++ ,
int double.
double
. (, C++
.)
. :
3.67 X 10'^ 367 000 000 000 000 000.0
C++ 3.6717.
5.89 X 10-' 0.00000589
5.89-6. ( . exponent),

.
,

. , ,
,
. , 3.494
( 34900.0),
. , -
; . , 3.49-4
0.0349.
, .
( ),
, .
,
, .
doubl
int. C++ 1nt
32 767 double 10^^^
2.3. 69

double
double (),
single ? C++ ,
, .
.
,
( ,
). ,
. - ,
, C++ doubl . C++
, ;
f 1 oat. , C++ ,
long double. ,
.


1nt double C++ .
. 2.1.
(
).
, ,
.
, ,
C++.

, ,
1nt double. , long
double:
long double big_number;

long long int .


:
long big_toatl:
long int big_total:

,
b i g t o t a l , .
, , long , long int, long double.
, , i nt,
. ,
double, .
, , (, 392.123),
, (3.921232).
, ()
, .
70 2. C++

, C++ ,
int, double long.
,
,
long.

2 . 1 .


short 2 -32 768 32 767


( short int)

int 4 -2 147 483 648 2 147 483 647


long 4 -2 147 483 648 2 147 483 647
( long int)

float 4 10"^^ 10^^ 7


double 8 10"^^^ 10^^^ 15
long double 10 10-^932 ^^mi ^g ^^

,
. .
, .
float, double long double .
, .

char
, ,
, C++
.
. char ( . cha
racter ). ,
, .
char symbol letter:
char symbol. l e t t e r ;

char ,
, . , ' ' ' +', ' '. ,
, ,
.
, .
, ,
, cout, ,
2.3. 71

. .
2.1:
"Enter the number of candy bars 1n a package\n";

,
, .
, '' "" . '' -
char, char, ""
, .
, ,
char. ,
.
char , 2.2.
,
, .
, ,
.
char 1,
,
, .
, .
2.2 ,
, ,
, JB.
2.2. char

#include <1ostream>
using namespace std;
int mainO
{
char symbol 1, symbol 2, symbol 3;

cout "Enter two i n i t i a l s , without any periods:\n";


cin symbol 1 symbol 2:

cout "The two i n i t i a l s a r e : \ n " :


cout symbol! symbol2 endl;

cout "Once more with a space:\n":


symbol 3 = ' ' ;
cout symbol 1 symbols symbol2 endl;

cout "That's a l l . " ;

return 0;
}


Enter two i n i t i a l s , without any periods:
J
72 2. C++

The two initials are:


JB
Once more with a space:
J
That's all.

bool
, , bool.
C++ ISO/ANSI (International
Organization for Standardization/American National Standards Institute).
bool
(1815-1864),
.

, true () false {).
, 2.4.
bool.


,
. , :
1nt 1nt_var1able:
1nt_vandble = 2.99:
. 2.99 doubl ,
1 nt_vari abl - 1 nt. ,
. ,
, .
,
, , intvariable 1nt,
3, 2.99, 2. ( ,
double
1nt, .)
, 2.99
double. ,

1nt int_variable:
double double_variable:
double_variable = 2.00:
1nt_variable = double_variable:
TOT , 2.00c ,
. doubl , 1 nt.
2.00 2, .
int_variable double_var1 able ,
.
2.3. 73


, , -
,
. , 1 nt 2.99,
2, 2.99, .
, ,
2.99, , .
,
. , 1 nt
double. :
double double_var1able:
double_var1able = 2;
clouble_variable 2.0.
char 1nt (, 65),
, int char (, 'Z'),
. C++
, ,
. char ,
int,
. ,
.
^ :
.
, ,
.
,
, .
bool (short,
int long), bool. ,
, . ,
, ,
: bool, fal -
se, true. bool
, true 1, false 0.


C++
(+), (-), (*)
(/). ,
2.1 * ,
. ( , .)
total_we1ght = one_we1ght * nuniber_of_bars;
74 2. C++

1 nt,
double .
(
). 1 nt, 1 nt.
double, double. ,
base_amount increase 1nt,
base_amount + increase
' i nt.
doubl , doubl . ~, * /.
,
. , 7.0/2 7.0 double,
double 3.5. 7/2
i nt, 3.
,
. , 6.0/2 6.0 double,
doubl 3.0, .
6/2 int,
3, .

. double,
, .

, . 10/3 3 ( 3.3333...),
5/2 2 ( 2.5), 11/3 3 ( 3.6666...),
, .
, i nt
/, %,
. , 17 5 3 2
. / 17 5 3, % 2.

cout "17 divided by 5 is " (17/5) endl;
cout "with the reminder of " (17^5) endl;
:
17 divided by 5 is 3
with the reminder of 2
Ha . 2.1 , / ^ int.

. 2 . 1 .
2.3. 75

int
/ ^ C++ .
,
, .
.
. ,
.

, :
(X + ) * Z
X +( * Z)


z. z
. ,
(, . .),
C++
. .
,
.
* +. ,
X+ * Z

, .
,
, ,
.
, .
2.

C++ . 2.2.
2.2.
++

h^ - b*b - 4**
{ + 2) *( + z)
1
xUx-v3 1/(* + -)
^ ( + )/( - d)

:
/
. ,
76 2. ++

. , , ,
,
. , , 1;
. $5000 .
,
+-:
total_price = 5000 * (feet/5280.0);

5280 . 15 000
:
5000 * (15000/5280.0)

15000/5280.0, 2.84.
5000 2.84 14200.00. , ,
, $14 200.
, feet int
, :
total_price = 5000 * (feet/5280);

- ,
. ,
int, feet/5280, 15000/5280,
2, 2.84. total price
5000 * 2, 10000.00.
14200.00, $4200. ,
totalprlce. double,
. , feet
double, .


15.
C++:
-\- +
] + ;
Z+2

16.
, ,
char?
= '';
b = ':
= ;
cout b '';

17. ,
, number int?
number = (1/3) * 3;
cout " (1/3) * 3 is equal to " number;
2.4. 77

18. C++,
1 nt
.
/ ^.
19. , ^
, :
double = 20:
double f:
f = (9/5) * + 32.0;

) f ;
) , ,
;
) ,
.


C++
. :
=
:
= ()
, +, - . .
.

count += 2; count = count + 2 ;
total -= discount; total = total -discount;
bonus *= 2; bonus = bonus * 2;
time /= rush_factor; time = time / rush_factor;
change %= 100; change = change % 100;
amount *= cntl + cnt2; amount = amount * (cntl + cnt2);

2.4.
, , !
! !
! , .
, -, , -.

, ,
, ,
.
78 2. ++

.
.
,
. ,
,
.



. ,
, ,
. ,
,
40 . 40 ,

rate*40 + 1.5*rate*(hours - 40)


( rate , ,
hours .) -
40 ,
(hours-40),
. ( ,
rate = 1 hours = 10.
.)
, 40 , :
rate*hours
,
40 ,
. , :
, (hours > 40)
, :
gross_pay = rate*40 + 1.5*rate*(hours - 40):
. :
gross_pay = rate*hours:

C++ , .
if...else. ,
:
i f (hours > 40)
gross_pay = rate*40 + 1.5*rate*(hours - 40);
else
gross_pay = rate*hours;

, , 2.3.
. 2.2 if...else. ,
.
2.4. 79

.
. _ (
hours > 40) .
if...else,
. _ , -
paropJAj _. ,
,
if...else. , , if...else
.


if {_)
JA
else
_


if {_)
{
__1
_2

_
}
else
{
_J.
__2

__
}

. 2.2. if...else

2.3. if...else
linclude <iostream>
using namespace std;
int mainO
{
int hours;
double gross_pay. rate;

cout "Enter the hourly rate of pay: $";


cin rate;
cout "Enter the number of hours worked,\n"
"rounded to a whole number of hours: ":
cin hours;
if (hours > 40)
gross_pay = rate*40 + 1.5*rate*(hours - 40);
el se
grosspay ^ rate*hours: i^
80 2. C++

2.3 ()
cout.setfdos: .-fixed);
cout.setfdos: ishowpoint):
cout.precision(2);
cout "Hours = " hours endl;
cout "Hourly pay rate = $" rate endl;
cout "Gross pay = $" grossj)ay endl;

return 0;
}

1
Enter the hourly rate of pay: $20.00
Enter the number of hours worked.
rounded to a whole number of hours: 30
Hours = 30
Hourly pay rate = $20.00
Gross pay = $600.0

2
Enter the hourly rate of pay: $10.00
Enter the number of hours worked,
rounded to a whole number of hours: 41
Hours = 41
Hourly pay rate = $10.00
Gross pay = $415.00

if...else .
( ) ,
true (), false ().
,
, . 2.3. ,
, ==,
!=, <=, >=. , ,
! =. (
.) !=
,
1 f ...el se .
true, ,
false .
, C++ &&,
. , ,
2 7:
(2 < X) && (X < 7)

&&,
, ,
.
2.4. 81

2.3.
C++
C++

X + 7 == 2* x-^1 = ly
ans != ' ' ans 'ri
count < m + 3 count <^
time <= l i m i t time < limit

time > l i m i t time > limit
age >= 21 age > 21

, ,
C++ 11. , ,
12:
( < 0) II ( > 12)
11, ,
, .
, , 1 f ...el se
,
. , if...else,
, &&,
:
tf ( (temperature >= 95) && (humidity >= 90) )

, , ,
.
,
, !. , !
. ! ( < ) : .
i f ...el se ,
, :
i f (!( < ) )

! .
if...else :
if (X >= )
82 2. C++

&&

, &&.
( )
(_1) && {_2)
( if...else)
if ( (score > 0) && (score < 10) )
cout "score is between 0 and 10An":
else
cout " score is not between 0 and 10.\n ";
score 10,
, .

11

, 11.
( )
{__1) 11 (_2)
( if...else)
i f ( ( = 1) II ( = - ) )
cout " is 1 or X equals y.\n";
else
cout "x is neither 1 nor equal to y.\n ";
x 1 (
), ! , .

!,
, .
,
i f ...el se .
if...else,
i f. :
if (salary > minimum)
salary = salary + bonus:
cout "salary = $" salary:

i f. sal
minimum ,
. salary minimum,
. i f
, cout,
sal i f.
2.4. 83

:

, :
if (X < Z < ) //
cout "z is between x and .":
, , ,
, . ,
, C++.
,
, > ==. z
C++ :
if ( (X < Z) && (Z < ) ) //
cout "z is between x and y.":

: = ==
, C++ ,
,
. ,
-
,
. .

= == .
if...else:
if ( = 12)
_
else
_

, ,
12, = ==. , ,
, ,
. , , , = 12
,
. C++ ,
, , + 12 2 + 3. ,
. ,
bool, 1nt
bool true false.
12, ,
true. , 1 f ...el se = 12
, true,

if,..else, _.
84 2. C++

, !
12, (12 = ),
; .
, , :
1f (12 == X)
_
else
_

, , = ==
, ,
, . C++
,
1 f ...el se. ,
,
. ,
. if...else
, ,
.


, if...else ,
.

. ( ,
. 2.2)
, 2.4.
, , .
C++
, . ,
if...else . 2.2
. 2.4 if...else
, .
2.4. if...else
i f (my_score > your_score)
{
cout "I win!\n";
wager = wager + 100;
}
else
{
cout "I wish theese were golf scoresXn";
wager = 0; ,
}
1f...else JA, _,
. ,
2.4. 85

- ,
.
if else
, .
el se, 1 f ...el se ,
,
if...else.


20. if...else, .High,
score 100, Low . score
i nt.
21. , savings expenses
double. if...else, Solvent,
savings expenses
expenses , savings
expenses. savings expenses,
Bankrupt, .
22. if...else, Passed,
exam 60 programsdone
10. Fai -
led. exam programs_done int.
23. if...else, Warning,
temperature 100 pressure
200.
. temperature pressure int.
24. :

, ( ),
, (-1),
(+2). C++,
.
25. :
Jt^- 4: + 3
, , ,
(+1) (+3).
C++, .
26. ,
? .
a)if(O)
cout " is true";
else
86 2. ++

cout " 1s false":


cout endl;
6)1f(l)
cout "1 1s true":
else
cout "1 Is false":
cout endl:
B)lf(-l)
cout "-1 1s true":
else
cout "-1 Is false":
cout endl:


,
. , 2.3 .
100 , ,
, 100 . ,
, . ++
.
while while.
,
.
2.5 while,
. , { }
whi 1 , .
,
, .
whi 1 .
2.5 ,
Hello. . ,
.
2.5. while
#1nclude <1ostream>
using namespace std;
Int ma1n()
{
Int count_down;

cout "How many greetings do you want? ":


c1n count_down:

while (count^down > 0)


{
cout -Hello ";
count_down = count_down - 1:
} -
cout endl:
2.4. 87

cout "That's a l l ! \ n " ;

return 0;
}
1
How many greetings do you want? 3
Hello Hello Hello
That's a l l !

2
How many greetings do you want? 1
Hello
That's a l l !

3
How many greetings do you want? 0
That's a l l !

whi 1 e, ,
. , ,
. (. 2.5) ,
, countdown .
, whi
le. 3,
count_down. , whi 1,
, count_down
, . , .
:
cout "Hello ";
count_down = count_down - 1;

, Hal 1, count_down
.
, .
while , ,
That' s al 1!.
Hello.
while . 2.3. _-
if...else.
, . . 2.3
:
, . ,
.
, while , .
,
while. ,
: true fal se. countdown > .
88 2. C++

2.5, true, countdown


. fal se,
, , while.
, .
, ,
countdown 2.5.
. ,
.
, while .

wh11 {_) '


{
_1
_2

_

^

while {_) "

. 2.3. while

: whi 1 .
, .
2.5.
,
, .
, whi 1 ,
, .
, whi 1 ,
. , ,
,
, do...while.
whi 1 ,
. do...whi 1 . 2.4,
- 2.6.
do...whi 1 , .
, whi 1 :
, ,
, . .
2.4. 89


do

_1
<^ ~_2

_
] while {_):

. ^'^"""^--^
/^
do

whi 1 (__);

. 2.4. do...while

2.6. do...while
#1nclude <1ostream>
using namespace std:
int mainO

char ans;

do
{
cout "\";
cout "Do you want anpther greeting?\n"
"Press for yes, n for no,\n"
"and then press Enter: ":
cin ans;
} while (ans == 'y' || ans = 'Y');

cout "Good-Bye\n";

return 0:


Hello
Do you want another greeting?
Press for yes. n for no.
and then press Enter:
Hello
Do you want another greeting?
Press for yes. n for no.
and then press Enter: Y
Hello
Do you want another greeting?
Press for yes. n for no.
and then press Enter: n
Good-Bye
90 2. C++




. , .
, . , + -,
; +7 -7. C++
, ++ --.
, .
, 1 nt.
1nt, ++ , --
. ++ -- . , :
1nt = 1. m = 7;
++;
cout "The value of n is changed to " n endl;
m;
cout "The value of m is changed to " m endl:

:
The value of n is changed to 2
The value of m is changed to 6

, C++ ++.

. , 2.5 countdown
:
count_down = count_down - 1;

C++
, whil
:
while (count_down > 0)
{
cout "Hello ";
count_down;
}

:
, $50
2 % . ,
$100 ( ,
)?
.
$50 2 % $50, $51.
$51 2 % $51, $52,02.
$52,02 2 % $52,02 . .
2.4. 91

balance.
:
balance = balance + 0.02 * balance;

, bal
100.00, , ,
$100. ,
.
count. while,
:
balance = balance + 0.02 * balance:
count++:

balance count
. .
2.7.
2.7. ,
#1nclude <1ostream>
using namespace std:
int mainO
(
double balance = 50.00;
1nt count = 0;

cout "This program tells you how long 1t takes\n"


"to accumulate a debt of $100. starting with\n"
"an initial balance of $50 owed A n "
"The interest rate is 2% per month.\n";

while (balance < 100.00)


{
balance = balance + 0.02 * balance;
count++;
}

cout "After " count " months An";


cout.setf(ios::fixed);
cout.setf(ios:;showpoint);
cout.precision(2);
cout "your balance due will be $" balance endl;

return 0;
)

This program tells you how long it takes
to accumulate a debt of $100. starting with
an initial balance of $50 owed.
The interest rate is 2% per month.
After 36 months.
your balance due will be $101.99
92 2. C++

:
wh11 dc.whi 1 ,
, while.
, , -
.
,
, . ,
, [ , .
,
. ;
, 12. 2, 4,
6, 8 10, , .
X = 2:
while (X != 12)
{
cout X end!;
X = X + 2;
}
2,
12. , whi 1 ,
, .
, ,
12. ,
, :
X = 1;

,
. 11 13,
12, ,
12.
,
(== !=).

.
:
while ( < 12)

.
,
- . ,
, ,
.
, Ctrl+C ( ,
Ctrl, ).
2.5. 93


27. ,
1 nt?
X = 10:
while ( > 0)
{
cout X encil;
X = X - 3;
}
28. ,
> <?
29. ,
1 nt?
X = 10;
do
{
cout X endl:
X = X - 3;
} while (x > 0);
30. ,
int?
X = -42;
do
{
cout X end1;
X = X - 3;
} while (X > 0);
31. while dc.while?
32. ,
int?
X = 10;
while ( > 0)
{
cout X endl;
X = X + 3;
}
33. C++, 1 20,
. .

2.5.

, .


, . ,
94 2. C++

.

. , , ,
.

,
.
, . ,
.
, . , ,
if...else, while do...while,
. ,
.
, ,
.
,
. ,
. ,
. , 2.7 , whi 1 ,
, .
,
. ,
, , ,
. ,
.
. , ,
, ,
, - ,
,
. , ,

.

,
.
. C++, ,
. // (
) C++ .
//
.
.
,
.
2.5. 95

C++ ,
/* */.
,
,
:
/* , .
,
.*/

,
. , ,

. .
, (// /* */) ,
. .
, .
,
-.
. - , ,
. ,
.
,
, .
, , ,
:
distance == speed * time // .
2.8
.
: , ,
, ,
. , ,
. ,
, ,

.
2 . 8 .
// .
// : health. (
// , .)
// : .
// : you^yourmachine.bla.bla
// : 2
// : , , .
// : 23 2004 .
finclude <iostream>
using namespace s t d ;
int mainO j ^
96 2. ++

2.8 {)
{
const double NORMAL = 98.6; //
double temperature;
cout "Enter your temperature: ":
Gin temperature;

1f (temperature > NORMAL)


{
cout "You have a fever.\n";
cout "Drink lots of liquids and get to bed.\n";
}
else
{
cout "You don't have a fever.\n";
cout "Go study An";
. }
return 0;
}

Enter your temperature: 98.6
You don't have a fever.
Go study.


.
, . ,
- 10,

. ,
. :
,
, . ,
10 .
, -
. ,
. ,
, 11, ,
, , .
.
BRANCH__COUNT WINDOW__COUNT,
10.
, BRANCHCOUNT.
C++ ?
, ; :
int BRANCH_COUNT = 10;
int WINDOW COUNT = 10;
2.5. 97

: -
. C++

. ,
. ,
const (; . constant
). :
const 1nt BRANCH_COUNT = 10:
const int WINDOW_COUNT = 10;

,
:
const int BRANCH_COUNT = 10. WINDOW_COUNT = 10;


. const .
, const,
.
C++ ,
.
,
, ,
.
. , BRANCH_COUNT
10 11, .
,
. ,
, 100 1 .
,
, .
, const,
2.8.

, const
,
. const.

const _ _ = :


const 1nt MAXJRIAE = 3;
const double PI = 3.14159:
98 2. G++


34. if...else
. ,
.
.
if ( < 0) { = 7: cout " is now positive.";}else
{x = -7: cout "X is now negative.";}

35. , ?
// cout "Hello from":
cout "Self-Test Exercise";

36. ,
( 1 3,78533 ).
. ,
.

.
, .
,
.
,
.
,
.
, - ,
, ,
.
, if...else
, if ,
.
, do...whi 1
, while .

.
const.
,
, .
,
.
99



1. 1nt feet = 0. inches = 0;
int feet(O). inches(O):

2. int count = 0;
double distance =1.5;

int count(O);
double distanced.5):

3. sum = nl + n2:

4. length = length + 8.3;

5. product = product * n;
6.
.
#include <iostream>
using namespace std;
int mainO
{
int first, second, third, fourth, fifth;
cout first " " second " " third
" " fourth " " fifth endl;
return 0;
}
7. Ha . :
) speed;
) pay_rate;
) max_score.
8. cout "The answer to the question of\n"
"Life, the Universe, and Everything is 42.\n";
9. cout "Enter a whole number and press Enter: ";
cin the_number;

10. cout.setf(ios::fixed);
cout.setfCios::showpoint);
cout.precision(3);
11. finclude <iostream>
using namespace std;
int mainO
{
cout "Hello worldXn"; ,
return 0;
100 2. ++

12. #include <iostream>


using namespace std;
int mainO
{
int nl. n2. sum:
cout "Enter two whole numbers\n":
cin nl n2;
sum = nl + n2;
cout "The sum of " nl " and " n2
" is " sum endl:
return 0;
}
13. cout endl "\t";
14. #include <iostream>
using namespace std;
int mainO
{
double one(l.O). two(1.414). three(1.732). four(2.0).
five(2.236);
cout.setf(ios::fixed);
cout.setf(iOS::showpoint);
cout.precision(3);

cout "\tN\tSquare Root\n";


cout "\tl\t" one endl
"\t2\t" two endl
"\t3\t" three endl
"\t4\t" four endl
"\t5\t" five endl;
return 0;
}
15. 3*x
3*x +
(x + y)/7 // , + /7 .
(3* + y)/(z + 2)
16. bcbc
17. (1/3) * 3 is equal to 0
1 3 i nt, /
, , 1/3 , 0.3333....
* 3, 0.
18. #include <iostream>
using namespace std;
int mainO

{
int numberl. number2;

cout "Enter two two whole numbers: ";


cin numberl number2;
101

cout numberl " divided by " number2


" equals " (numberl/number2) endl
"with the reminder of " (numberUnumber2)
endl;

return 0:

19. a) 52.0;
) 9/5 1 int.
i nt,
;
) f = (9.0/5) * + 32.0;

f = 1.8 * + 32.0;

20. if (score > 100)


cout "High";
else
cout "Low";

\
.
21. i f (savings >= expenses)
{
savings = savings - expenses;
expenses = 0;
cout "Solvent";
}
else
{
cout "Bankrupt";
}
\
.
22. if ( (exam >= 60) && (programs_done >= 10) )
cout "Passed";
else
cout "Failed";

\
.
23. if ( (temperature >= 100) || (pressure >= 200) )
cout "Warning";
else
cout "OK";

\
.
102 2. C++

24. (X < -1) II (X > 2)


25. (1 < X) && (X < 3)
26. ) 1s false ( ,
Int false);
) 1 1s true ( ,
Int true);
) -1 1s true ( ,
1nt true).
27. 10
7
4
1
28. , ( < 0)
, wh11
.
29. , 27.
30. .
, :
-42
31. do...wh1le .
whi 1 , .
32. . :
10
13
16
19
(
, ,
- ,
.)
33. #1nclude <1ostreai7p>
using namespace std;
1nt ma1n()

1nt n = 1;
while (n <= 20)
{
cout n endl;
++:
}
return 0;
}
34. lf (X < 0)
{
103

X = 7:
cout " 1s now positive.";
}
else
{
X = -7:
cout "x is now negative.":
}
35. - , .
:
Self-Test Exercise
36. #include <iostream>
using namespace std;
int mainO

{
const double LITERS_PER_GALLON = 3.78533:
double gallons, liters:

cout "Enter the number of gallons:\n":


cin gallons:

liters = gallons*LITERS_PER_GALLON:
cout "There are " liters " liters in "
gallons " gallons.\n":

return 0:


1. 1 35 273,92 .
,
, ,
.
, .
2. ,
, ,
. ,
. ,
, . ,
. ,
, .
, , ,
. , 0,1 % -
. ( 0.001
double) , const.
.
104 2. C++

3. ,
. ,
,
,
,
.
, const.
.
4. .
,
. , $1000,
15 %, 18 .
$1000 15 %, $150.
, 1,5 ,
$225.
, $775.
(
) . ,
$1000 18, $55,56.
, $775 ,
$1000, .
, : , ,
.

.
5. , ,
.

, .
, ,
, ,
.
, ,
,
.
.
6. $16,78
. .
: 6 %
, 14 % , 5 %
$10
.
, $35
. ,

105

, , 1
, .

.
7. - .
200 ,

. - ,
, . ,
.
,
, .
, ,
5,6 %. (
0,056) - .
. ,
, 2.4.
8. $1000
. , 18 % (
1,5 % ) $50. $50
, .
1,5 % $1000, $15. $35
, $965,00.
1,5 % $965,00, $14,48. $35,52
($50 - $14,48) . . , ,
, ,
.
. (
, ,
, ,
.)
,
, . ,
. $50,
, .
$50,
.
$50 75 .
9. , 10
, , (
) (
, ). 10
.
.
3

,
, .

, ,
, .
, +- ,
, .
3 C++,
: , .
, .

3 . 1 .
,
,
, . 1,
.
: ,
. .
, C++ .
(
^ ^).
, ,
, -.
,
, , , .
3.2. 107

, C++
.
, , C++
.


, .
,
, .

3.2.
C++ ,
.
, , .


sqrt,
. ,
9.0, , 3.0. ,
, , ,
, . ,
.
, ,
.
. ,
the_root 9.0,
:
the_root = sqrt(9.0):
sqrt(9.0) .
, 9.0, .
, ,
,
. , , sqrt,
doubl . ,
bonus = sqrt(sales)/10;
sales bonus double. sqrt
; , :
bonus = (sqrt(sales))/10:
cout, :
cout "The side of a square with d^red^ "
area " 1s " sqrt(area);
108 3.


, ,
, . ,
.
, .

_(_)
_
_1, _2 _

side = sqrt(area):
cout "2.5 to the power 3.0 is "
pow(2.5. 3.0);

3.1 , sqrt.
,
.
, .
sqrt , .
3 . 1 .
// ,
// .
#1nc1ude <1ostream>
#include <cmath>
using namespace std;

i n t mainO
{
const double COST_PER_SQ_FT = 10.50:
double budget, area. length_side;

cout "Enter the amount budgeted"


" for your dog house $";
cin budget:

area = budget/COST_PER_SQ_FT:
length_s1de = sqrt(area):

cout.setf(ios::f1xed):
cout.setfdos: :showpo1nt):
cout.precision(2);
cout "For a price of $" budget endl
"I can build you a luxurious square"
"dog house\n"
"that is " length_side
" feet on each side.\n":

return 0:
3.2. 109


Enter the amount budgeted for your dog house $25.00
For a price of $25.00
I can build you a luxurious square dog house
that is 1.54 feet on each side.

3.1:
#include <cmath>

finclude <iostream>
. 2,
include. (<>) .

, include .

. ,
iostream 1 cout;
iostream. cmath sqrt
; cmath.
- ,
include
, :
#include <cmath>
, .
(
). , , #
, ,
# i ncl ude. i ncl ude
, .
,
#include <iostream>
using:
using namespace std:
cin cout
std. .
include -
cmath, using.
i ncl ude
usi ng. ,
. ,
.

-. C++
.
110 3.

,
.
, -, include
, . ,
,

.
. 3.1, ;
4. , ,
(abs 1 abs), ,
stdl 1,
:
finclude <stdl1b>
( , sqrt)
cmath.
3 . 1 .



sqrt double double sqrt(4.0) 2.0 cmath

pow double double pow(2.0. 3.0) 8.0 cmath

abs int int abs(-7) 7 cstdlib
abs(7) 7
i n t
labs long long labs(-70000) 70000 cstdlib
labs(70000) 70000
long
fabs double double fabs(-7.5) 7.5 cmath
fabs(7.5) 7.5
doubl
ceil double double ceil(3.2) 4.0 cmath
ceil(3.9) 4.0

floor double double floor(3.2) 3.0 cmath
floor(3.9) 3.0

, ,
. abs i nt,
labs long, fabs double.
stdlib,
fabs cmath. (,
3.2. 111

(floating-point).
fabs . floating-point absolute value.)
pow
cmath. . ,
result ^, :
result = pow(x. ) ;

9.0,
(3.0)^'^ 9.0:
double result, = 3.0. = 2.0;
result = pow(x, ) :
cout result;

, pow
9.0, 9, double, 1nt.
, ,
.
, , ,
. C++,
, , ,
, .
. ,
1 nt
double. ,
1 nt , doubl .
pow
. , pow ,
. C++
, pow
.


, 9/2 ,
4 4.5. double
( ),
. , 9/2.0 4.5.
,
.
, , ,
?
int total_candy. number_of_peopl:
double candy_per_person;
... totaljoandy 9,
number_ofj)eople 2. , . . ..

candy_per_person = total_candy/number_of_people;
112 3.

, totalcandy number_of_peo-
ple, double, 4, 4.5. ,
candyperperson double, .
4 doubl
candy_per_person ! , 4
4.0 candy_per_person 4.0, 4.5.
,
, .
, C++
1 nt doubl , . ,
9 double:
stat1c_cast<double>(9)

stat1c_cast<double> ,
, 9, , double.
.
doubl ,
.
9 1nt double
answer 4.5.
double answer;
answer = static_cast<double>(9)/2;

,
,
. .
9 double, 9.0 stat1c_cast<double>(9.0)
. ,
. ,
candy_per_person 4.5.
total_candy stat1c_cast<double>(total_candy):
i n t total_candy. number_of_people;
double candy_per_person;

. . . total_candy 9, a number_ofj)eople
2. , . . . .

candy_per_person =
stati c_cast<doubl>(total_candy)/number_of__people;

.
,
.
candy_per_person =
static_cast<double>(tota1_candy/number_of_people); //
candy_per_person 4.0, 4.5.
3.2. 113

int double
stat1c_cast<double>
, double. , stat1c_cast<double>(2)
2.0.
. ( double,
, .)

static_cast<double>(fib/p(3^ewHe_r^/7a_7^t)

int total_pot. number_of_winners;
double your_winn1ngs:

your_winnings =
static_cast<double>(total_pot)/number_of_w1nners;


C++
static_cast<THn>. C++
:
, ,
. , 9 double :
double(9)

, candy_per_person double, total_


cmdy number_of_people - 1nt,
candy_per_person =
static_cast<double>(total_candy)/number_of_people;

candy_per_person =
doubleCtotal_candy)/number_of_people;

Ho stat1c_cast<double>(total_candy) double(total_candy)
, ,
C++ .

:

, 11/2, ,
5, 5.5.
, ,
.
114 3.

:
double d;
d = 11/2:

, ,
. 5
double d,
. , d double,
5.0, 5.5.

1. .
sqrt(16.0) sqrt(16) pow(2.0. 3.0)
pow(2. 3) pow(2.0. 3) p o w d . l . 2)
abs(3) abs(-3) abs(O)
fabs(-3.0) fabs(-3.5) fabs(3.5)
ceiKS.l) 0911(5.8) floor(5.1)
floor(5.8) pow(3.0. 2)/2.0 pow(3.0. 2)/2
7/abs(-2) (7 + sqrt(4.0))/3.0 sqrt(pow(3. 2))
2.
C++.
-sjx+y ^^^ ^ area fudge

^time + tide - + 1^ -Aac i i


nobody la ' '
3. C++,
( 3,14159).
_1,
cmath const double M_PI.
4. ,
:
) #1nclude <iostreanp>
( #);
) # 1 1 ude.

3.3. ,

, , .
,

, .
.
3.3. , 115


,
(main),
.
3.2 total_cost
, .

, . total_cost
, .
, , .
3.2.
#1nGlude <1ostream>
using namespace std;

// .
double total_cost(int number_par, double price_par);
// , 5 % ,
// number_par , 1_.

int mainO
{
double price, bill:
int number:
cout "Enter the number of items purchased: ":
cin number:
cout "Enter the price per item $":
cin price:

// .
bill = total_cost(number, price):

cout.setf(ios::fixed):
cout.setfCios::showpoint):
cout.precision(2):
cout number " items at "
"$" price " each.\n"
"Final bill, including tax. is $" bill
endl:

return 0:
}
// .
double total__cost(int number_par, double price_par) // .
// .
{
const double TAX_RATE = 0.05; / / 5 ^
double subtotal;

subtotal = price_par * numberpar; ^


116 3.

3.2 {)
return (subtotal + subtotal*TAX_RATE);
}
// .
// .

Enter the number of items purchased: 2
Enter the price per item $10.10
2 items at $10.10 each.
Final b i l l , including tax. is $21.21

,
. , .
C++ ,
, .
total_cost 3.2:
double total_cost(int number_par. double price_par);

,
, total cost,
. total cost ,
int, double. number_par price_par
.
, ,
.
,
par,
. , .

, , total cost double.
, 3.2:
bill = total_cost(number, price);
.
, ,
total_cost . int,
double, bill double, ,
double. ,
.


,
. ,
.
.
3.3. , 117


__ _{_);
__ _

_ :
_1 __1, _2 __2
_ __

// .
double total_waight(int number, double wa1ght_of_one):
// number .
// wa1ght_of_one.

, 3.2 ,
.
,
.
.
, .
, , .
, ,
.
, ,
,
.
.
. ,
. ,
, .
,
.
return. ( ,
, .)
return return,
. 3.2 return:
return (subtotal + subtotal*TAX_RATE):



(subtotal - subtotal*TAX_RATE)

. return
:
return subtotal + subtotal* RATE;
118 3.

return, ,
. ,

. 3.2 return
, ,
. return .
,
3.2:
b i l l = total_cost(number, price):

, number price
number_par price_par.
3.2 number 2, price
10.10, number_par price_par 2
10.10. ,
, .
, .

1. .
, ,
.
2.
, . .
3.
(, ,
numberpar,
2).


, , :
,
;
,
1 .
;
,
. ,
, cout
return.

3.2
. 3.1.
3.3. , 119

3.2
1. number price 1
2 10.10 (. 3.2).
2. , :
11 = total_cost(number, price):
3. number ( 2) number_par,
price ( 10.10) price_par:
/ /
double total_cost(int number_par. double price_par)
{
const double TAX_RATE = 0.05: / / 5 ^
double subtotal-
subtotal = price_par * nuniber_par:
return (subtotal + subtotal*TAX_RATE):

:
//
double total_cost(int 2, double 10.10)
{
const double TAX_RATE = 0.05: // 5 ^
double subtotal:
subtotal = 2 * 10.10:
return (subtotal + subtotal*TAX_RATE):
}
4. , :
{
const double TAX_RATE = 0.05: // 5 ^
double subtotal:

subtotal = 2 * 10.10:
return (subtotal + subtotal*TAX_RATE):
}
5. return ,
return.
return (subtotal + subtotal*TAX_RATE):

total_cost(number, price)
(subtotal + subtotal*TAX_RATE), 21.21,

b i l l = total_cost(number, price):
bi 11 ( ) 21.21.

. 3 . 1 .
120 3.



. :
double total_cost(int number_par. double 1_):

double total_cost(1nt. double);

.
,

.
^
.

.

:

, . .,
(
). ,
, . ,
, ,
3.3.
grade. :
letter_grade = gradeCscore, need_to_pass):

, ,
, - ; .
grade ,
,
.
,
, .
, , ,
,
, .
, C++
, .
.
, ,
.
3.3. , 121

. 3.3.
// .
// : Pass () Fail ( ).
linclude <iostream>
using namespace std;

char grade(int received_par. int min_score_par);


// 'P'. Pass,
// received_par min_score_par.
// 'F' (Fail).

int mainO
{
int score. need_to_pass;
char letter_grade;

cout "Enter your score"


" and the minimum needed to pass:\n";
cin score need_to_pass;

letter_grade = grade(need_to_pass. score);

cout "You received a score of "


score endl
"Minimum to pass is " need_to_pass
endl;

if (letter_grade === 'P')


cout "You Passed. Congratulations!\n";
else
cout "Sorry. You failed.\n";

cout letter_grade
" will be entered in your record.\n";

return 0;

char grade(int received_par. i n t min_score_par)


{
i f (received^par >= min_score_par)
return 'P';
else
return 'F';


Enter your score and the minimum needed to pass:
98 60
You received a score of 98
122 3.

Minimum to pass 1s 60
Sorry. You f a i l e d .
F w i l l be entered in your record.


,
( , ,
). . 3.2
. ,
.
,
.
,
. , ;
, . 3.2.
return,
(
). , if...else
return , 3.3.


__ _(_):
___


__ _(_) -<
,{ '
6_1
_2

1 _
^^^\ __1 \
__2 \
? return
__ /

. 3.2. ,


. ,
, .
. 3.2, ,
,
.
3.3. , 123


,
, .
. , , :

. ,
, .
,
, ,
( ).
,
, C++.


5. :
finclude <iostream>
using namespace std;
char mysterydnt f1rst_par. i n t second_par);
1nt mainO
{
cout mystery(10. 9) "ow\n";
return 0;
}

char mysterydnt first_par. i n t second_par)


{
i f (f1rst_par >= second_par)
return 'W:
else
return 'H':
}
6. ,
1 nt .
7. ,
int double double,
.
8. ,
double. '',
, ' N', .
9. .
10. ()
?
124 3.

3.4.
, .


.
,
!
, -
. ,
, , .
- ,
, . ,
(
), ,
. , .
,

. , , .

.
:
, .
.
, .
3.4 newbal
. ,
. ,
$100 4,5 %, $104,50.
vacati onf und 100.00,
104.50:
vacation_fund = 100.00:
vacat1on__fund = new_bal(vacation_fund. 4.5):

3.4. ,

double new_bal(double balance_par. double rate_par);
//
// .
// balancejDar
// .
// rate__par
// .
// , rate_par 5.0.
// 5 ^ new_balance(100. 5.0) 105.00.
3.4. 125

1
double new_balance(double balance_par, double rate_par);
{
double 1nterest__fract1on, interest;

1nterest_fpaction = rate_par/100;
interest = interest_fraction*balance_par;
return (balance_par + interest);
}
2
double new_balanee(double balance_par. double rate_par);
{
double interest^fpaction. updated_balance;
intepest_fpaction = pate_pap/100;
updated_balance = balance_pap*(l + interest_fpactIon);
petupn updated_balance;
}
He ,
.
, ,
, .

. C++, ,
, ,
.
, C++. ,
: ,
, .
, .
. ,

.



, ,
. ,
,
.
,
.

.
(
,
).
126 3.

:

,
, .
.

. , , ,

.
, , .
, ,
. enie
, ,
.
, ,
, par.
3.5
total cost 3.2,
number_par 1__ number p r i c e .

3.5.


double total_cost(1nt number, double price):
/ / , 5 Z .
/ / number_par , price_par.


II
double total_cost(int number, double price)
{
const double TAX_RATE = 0.05; // 5 ^
double subtotal;

subtotal = price * number;


return (subtotal + subtotal*TAX_RATE);
}

:
,
. .
,
.
,
, ,
. ,
3.4. 127

, ,
.

.
. .
. -
, .


.
1. .
2. .
3. .
4. , .
5. .
2 3. .
1. . ,
. ,
2 3 .
2. 2 3
.
(, )
, .
,
, . ,
,
unitprlce. :
double u n i t p r i c e d n t diameter, double price):
// .
// diameter
// .
// price .


1 .
, diameter_small, diameterjarge, price_small pri-
cejarge.
4 . , ,

. 5 .
128 3.

2 3 unltprice.
. .
, :
price/area
area , , price -
, .
.
.
, (
) ^ - ( ), -
, 3,14159.
unltprice. .
1. .
2. ^.
3. (price/area).
C++ ,
.
, ,
. ,
C++,
C++. radius area
.
unitprice:
radius = :
area = * radius * radius:
return (price/area):

unitprice .
1-5 C++.

( 1)
, 2 3.
:
unitpr1ce_small = unitprice(diameter_small. price_sman):
unitpricejarge = unitpriceCdiameterJarge. pricejarge):

unitprice_smal1 unitpricejarge - double.


,
.
( )
.
3.4. 129

C++
unitprice:
// unitprice.
{
const double PI = 3.14159;
double radius, area:
radius = diameter/2:
area = PI * radius * radius:
return (price/area):
}
, const PI
. ,
:
radius = diameter/2:

2 ?
.
, . , 13-
6,5 . di ameter i nt,
2. , 2,
, 6.5, 6.
,
, . ,

.
.
? , 2 ,
, .
double.
2. , stat1c_cast<double>(2),
, 2
double. , 2
static_cast<double>(2),
double .
:
radius = diameter/static_cast<double>(2):

unitprice
3.6.
static_cast<double>(2) 2.0,
2.0.
, ,
. stati c_cast<doubl >(2) 2.0,

2, .
130 3.

.
3.6, 4 5, ,
cout,
if...else. ,
.
3.6.
/ / ,
/ / .
#inclucle <1ostream>
using namespace std;

double unitpriceCint diameter, double price):


/ / .
/ / diameter .
/ / price .

i n t mainO
{
i n t diameter_sman. diameterjarge:
double price_sman, unitprice_sman.
p r i c e j a r g e . unitprice_large;

cout "Welcome to the Pizza Consumers Union.Xn";


cout "Enter diameter of a"
"small pizza ( i n inches): ";
cin diameter_small:
cout "Enter the price of a small pizza: $";
cin price_small:
cout "Enter diameter of a"
" large pizza (in inches): ";
cin diameterjarge;
cout "Enter the price of a large pizza: $";
cin pricejarge;

unitprice_sman = unitpriceCdiameter^small, price_small);


unitprice large * unitpriceCdiameterjarge, pricejarge);

cout. s e t f ( i o s : : fixed);
cout.setf(ios::showpoint);
cout.precision(2);
cout "Small pizza:\n"
"Diameter = " diameter_small
" inchesXn"
"Price - $" price_small
" Per square inch = $" unitprice_small
endl
"Large pizza:\n"
"Diameter = " diameterjarge
" inches\n"
"Price = $" p r i c e j a r g e
" Per square inch = $" unitpriceJarge
endl;

i f ( u n i t p r i c e j a r g e < unitprice_small)
cout "The large one is the better buy.Vn";
3.4. 131

else
cout "The small one is the better buy.\n":
cout "Buon Appetito!\n";

return 0;
)
double unitpricednt diameter, double price)
{
const double PI - 3.14159;
double radius, area:

radius diameter/static_cast<double>(2);
area P I * radius * radius;
return (price/area);
}


Welcome to the Pizza Consumers Union.
Enter diameter of a small pizza ( i n inches): 10
Enter the price of a small pizza: $7.50
Enter diameter of a large pizza ( i n inches): 13
Enter the price of a large pizza: $14.75
Small pizza:
Diameter 10 inches
Price $7.50 Per square inch $0.10
Large pizza:
Diameter - 13 inches
Price = $14.75 Per square inch - $0.11
The small one is the better buy.
Buon Appetito!


To, ,
, , .
, ,
(
). , -
, ,
.
, $3,14. 1 ,
3,14159*1^, 3,14159. ,
, ,
$1,00. , ,
,
.
-
, ,
. ,
- . ,
,
132 3.

. ,
,
radius = dianieter/stat1c_cast<double>(2):

radius = diameter/2;
, 2, 8, 10 12,
. ,
. ,
( , ),
.

:

, . -
,
, (,
). ,
C++,
C++. C++,
. ,
, .
,
unitprice.

. , ?
12.
?
13. , ,
? (.
.)
14. .
15. unitprice.
3.6. ,
static_cast<double>(2) 2.0. ,

radius = diameter/static_cast<clouble>(2);

radius = diameter/2.0:

?
3.5. 133

3.5.
,
.

,
.
, , .
. ,
.


3.1.
sqrt. , , , ,
.
, ,
. ,
,
. .
, 3.7, avera
ge pea, esttotal,
- . ,
,
. esttotal averagepea
,
. ( 3.7,
,
: .)
3.7.
//
// ,
finclude <iostream>
using namespace std;

double est_total(1nt niin_peas. i n t max_peas. i n t pocl_count):


// .
// pod_count
// .
// min_peas
// max^peas
// .

int mainO
{
int niax_count. min_count. pod_count: ^
134 3.

3.7 ()
double averagejDea. yield: // .

cout "Enter minimum and maximum"


" number of peas in a pod: ":
cin min_count max_count:
cout "Enter the number of pods: ":
cin pod_count;
cout "Enter the weight"
" of an average pea (in ounces): ":
cin average_pea:

yield = est_total
(min^count. max_count. pod_count) * average_pea:

cout.setf(ios::fixed):
cout.setfdos: :showpoint);
cout.precisionO):
cout "Min number of peas per pod = "
min_count endl
"Max number of peas per pod = "
max_count endl
"Pod count = " pod_count endl
"Average pea weight = "
average_pea " ounces" endl
"Estimated average yield = "
yield " ounces"
endl;

return 0;
}
double est_total(int min^peas. int max_peas. int pod_count)
{
double average_pea; // est_total.
average_pea = (max_peas + min_peas)/2.0;
return (pod_count * average_pea):
}

Enter minimum and maximum number of peas in a pod: 4 6
Enter the number of pods: 10
Enter the weight of an average pea (in ounces): 0.5
Min number of peas per pod = 4
Max number of peas per pod = 6
Pod count = 10
Average pea weight = 0.500 ounces
Estimated average yield = 25.000 ounces
, ,
, . ,
,
, .
,
.
3.5. 135

, , -
.


, ,
^ . ,
, ^
.
, ,
- . ,
,
.

:
3.7 ,
. esttotal
. :
,
. ,

.
.



2 ,
const. , 3.6
PI,
3,14159:
const double PI = 3.14159;
3.2 const
:
const double TAX__RATE - 0.05: / / , 5 %.

, ,
, . ,
.
, .

.
, -
.
136 3.

3.8 ,
.
.
:
= X (paduycf
== (4/3) X 71 X (paduycf
, 3,14159.
:
const double PI = 3.14159;

3.8 PI ,
, , ,
.

, ,
: #inc1ude,
, .
,
#1nclude .

,
. -
, . ,
,
.
, const, -
, . ,
,
.
, ,
, .
C++
.
3.8.
// .
// .
#inclucle <iostream>
#1nclude <cmath>
using namespace std:

const double PI = 3.14159:

double areaCdouble radius);


// .
double volume(double radius);
// .
3.5. 137

1nt mainO
{
double rad1us_of_both, area_of_c1rcle, volume_of_sphere:

cout "Enter a radius to use for both a circleVn"


"and a sphere (in inches): ":
cin rad1us_of_both;

area_of_circle = area(radius_of_both):
volume_of_sphere = volume(rad1us_of_both):

cout "Radius = " rad1us_of_both " inches\n"


"Area of c i r c l e = " area_of_circle
" square 1nches\n"
"Volume of sphere = " volume_of_sphere
" cubic inchesNn";

return 0;

double areaCdouble radius)

return (PI * pow(radius, 2));

double volume(double radius)

return ((4.0/3.0) * Pl * pow(radius. 3 ) ) ; '


Enter a radius to use for both a c i r c l e
and a sphere (in inches): 2
Radius = 2 inches
Area of c i r c l e = 12.5664 square inches
Volume of sphere = 33.5103 cubic inches

,
,

,
, ,
.
, .
( )
.
, . ,

, .
,
.
138 3.

3.9
, . ,
, :
15- , ,
. , ,
, , ,
$600, $750.
minutes^worked
fee. , :
niinutes_worked = hours_worked*60 + minutes_worked;
,
, . ,

. , fee:
double feednt hours^worked. int minutes_worked)
{
int quarter_hours;
int minutesworked; // .

, mi nutes worked .
3.9. ,
// , ,
finclude <iostream>
using namespace std;

const double RATE = 150.00: // .

double feeCint hours_worked. int minutes_worked);


// hours_worked
// minutes_worked .

int mainO
{
int hours, minutes;
double bill;
cout "Welcome to the offices of\n"
"Dewey. Cheatham, and Howe.Xn"
"The law office with a heart.\n"
"Enter the hours and minutes"
" of your consultation:\n";
cin hours minutes;

bill = fee(hours, minutes);


// minutes fee

cout.setfCios: .-fixed);
cout.setfCios:ishowpoint);
cout.precision(2);
cout "For " hours " hours and " minutes
3.5. 139

" minutes, your b i l l is $" b i l l endl:

return 0;
}
double feednt hours_worked. int minutes_worked)
// niinutes_worked - ,
// minutes feeChours, minutes) .
{
i n t quarter_hours;

niinutes_worked = hours_worked*60 + minutes_worked:


quarter_hours = minutes_worked/15:
return (quarter_hours*RATE);
}


Welcome to the offices of
Dewey. Cheatham, and Howe.
The law office with a heart.
Enter the hours and minutes of your consultation:
2 45
For 2 hours and 45 minutes, your bill is $1650.00

std
:
#include <iostream>
using namespace std:

using namespace std;

std, ,
, .

using namespace std:


( , ),
.
,

,
.
using
. , ,
. ,
. using,
, .
, std,
using , .
140 3.

, 3.8,
us1 ng .
,
.
.
3.10.
/ / .
/ / .
#1nclude <iostream>
Unclude <cmath>

const double PI = 3.14159;

double areaCdouble radius);


/ / .

double volumeCdouble radius);


/ / .

int mainO
{

using namespace std;

double radius_of_both, area_of_circle. volume_of_sphere;

cout "Enter a radius to use for both a circleXn"


"and a sphere (in inches): ";
cin radius_of_both;
area_of_circle = area(radius_of_both);
volume_of_sphere = volume(radius_of_both);

cout "Radius = " radius__of_both " inchesXn"


"Area of c i r c l e = " area_of__circle
" square inchesNn"
"Volume of sphere = " volume_of_sphere
" cubic inchesXn";

return 0;

double areaCdouble radius)


{
using namespace std;

return (PI * pow(radius. 2));


}

double volume(double radius)


{
using namespace std;

return ((4.0/3.0) * PI * pow(radius. 3));


}
3.5. 141


16. , :
, , ?
17. , Functlonl Sam,
Funct1on2.
(,
)? ,
(,
)? , ,
(,
)?
18. ,
, ,
. , total Jnchesd. 2)
14, 1 2 14 (,
1 12 ). :
double totaljnchesdnt feet, int inches)
{
inches = 12*feet + inches:
return inches;
}
?
19. reacl_filter,
doubl .

, ,
, , .

: ,
3.11 ,
^ .
\ ( )
:
! = 1 X 2 X 3 X ... X /2

while.
, :
, w-1, -2 . . factorial
: product,
, .
, .
-- ( 2).
142 3.

3 . 1 1 . ,

int factorial (int n):
// n .
// n .

int factorial (int n)
{
int product = 1;
while (n > 0)
{
product = n * product;
n--: // n .
}
return product;
}
product
, --
. factorial 3,
product 3,
3*2, 3*2*1, whi 1 .
X = factorial(3);
6 ( 3*2*1).
, product 1
. , ,
, product
.

3.6.
- , :
.
- , .
- ! !
- , ? .
- .
- , , .
: , !.
- ,
!, .
- , , ,
, .
- , , .
- , , -.

+4-
,
3.6. 143

. , max:
, ,
.
.
,
,
.


, ,
.
:
double aveCdouble 1. double 2)
{
return ((nl + 2)/2.0):
}
,
. :
double ave3(double n l . double 2, double )
{
return ( ( n l + 2 + )/3.0);
}

,
. C++
. ,
ave3 :
double ave(double n l . double 2. double )
{
return ( ( n l + 2 + )/3.0):
}

ave ,
.
3.12 ave
. , .
, .

,
. ,
, ,
?
, .
3.12 ave , .
, ,
144 3.

: , ,
.
,
. ,
,
. ,
:
, .


.

/ .
,
.

3.12.
/ / ave.
#inclucle <iostream>

double ave(double n l , double n2);


/ / , nl 2.

double ave(double n l , double 2, double );


/ / , n l , 2 .

int mainO
{
using namespace std;
cout "The average of 2.0. 2.5. and 3.0 is "
ave(2.0. 2.5, 3.0) endl;

cout "The average of 4.5 and 5.5 is "


ave(4.5. 5.5) endl:

return 0;

double ave(double n l , double n2) / / ,

return ( ( n l + n2)/2.0);

double ave(double n l , double n2, double n3) / / .

return ( ( n l + n2 + n3)/3.0):
3.6. 145


The average of 2.0. 2.5. and 3.0 1s 2.5
The average of 4.5 and 5.5 1s 5

Ha . 2
/. 1nt,
. , 13/2 6.
doubl ,
. , 13/2.0 6.5. ,
.

,
. , ,
+, - . .

:

,
3.6. ,
.
,
. :
, , ,
.
, .
.
, , :
.
, ,
. :
double un1tpr1ce_rectangular
(1nt length, Int width, double price)
{
double area = length * width;
return (price/area):
}
,
. ,
, ,
. +4- ,
. un1tpr1ce
- ,
. , ,
3.13.
146 3.

3.13.
// , :
// .
#111 <1ostream>
double unitpriceCint diameter, double price):
// .
// diameter .
// price .
double unitprice(int length, int width, double price);
//
// length width .
// price .
int mainO
{
using namespace std:
int diameter, length, width;
double price_round, unit_price_round,
price_rectangular. unitprice_rectangular:
cout "Welcome to the Pizza Consumers Union.\n";
cout "Enter the diameter in inches"
" of a round pizza: ";
cin diameter;
cout "Enter the price of a round pizza: $";
cin price_round;
cout "Enter length and width in inches\n"
"of a rectangular pizza: ";
cin length width;
cout "Enter the price of a rectangular pizza: $":
cin price_rectangular;
unitprice_rectangular =
unitprice(length, width, price^rectangular);
unit_price_round = unitpriceCdiameter, price__round);
cout.setf(ios::fixed);
cout.setf(ios::showpoint);
cout.precision(2);
cout end!
"Round pizza: Diameter = "
diameter " inchesXn"
"Price = $" price_round
" Per square inch = $" unit_price_round
endl
"Rectangular pizza: Length = "
length " inchesVn"
"Rectangular pizza: Width = "
width " inchesXn"
"Price = $" price_rectangular
" Per square inch = $"
unitprice_rectangular
endl;
i f (unit_price_round < unitprice_rectangular)
3.6. 147

cout "The round one is the better buy.Xn";


else
cout "The rectangular one is the better buy.\n";
cout "Buon Appetite!\n";

return 0;
}
double unitpriceCint diameter, double price)
{
const double PI 3.14159;
double radius, area;
radius diameter/static_cast<double>(2);
area P I * radius * radius;
return (price/area);
}
double unitpriceCint length, int width, double price)
{
double area length * width;
return (price/area);
}

Welcome to the Pizza Consumers Union.
Enter the diameter in inches of a round pizza: 10
Enter the price of a round pizza: $8.50
Enter length and width in inches
of a rectangular pizza: 6 4
Enter the price of a rectangular pizza: $7.55

Round pizza: Diameter = 10 inches


Price = $8.50 Per square inch = $0.11
Rectangular pizza: Length = 6 inches
Rectangular pizza: Width = 4 inches
Price = $7.55 Per square inch = $0.31
The round one is the better buy.
Buon Appetite!


, mpg:
double mpg(double miles, double gallons)
// .
{
return (miles/gallons);
}
,
.
int, C++
doubl . :
cout mpg(45. 2) " miles per gallon";
148 3.

22.5 m11 es pre 11 on. C++ 45 45.0 ,


2 2.0, 45.0/2.0 22.5.
double,
1nt, C++ double.
, .
.
, mpg
:
int mpgdnt goals, 1nt misses)
// .
// (goals - misses).
{
return (goals - misses);
}
, , :
cout mpg(45. 2) " miles per gallon";
43 miles per gallon ( 43 45 - 2)
C++ mpg(45. 2) int,
mpg i nt.
, ,
.
:

, .

20. , score
:
double score(clouble time, double distance);

int score(double points):

final_score = score(x);
( double)?
21. , theanswer
:
double the_answer(double datal. double data2);

double the_answer(double time, int count);

X = the_answer(y, 6.0);
( double)?
149

22. , theanswer,
21.
X = the_answer(5. 6);
?
23. , theanswer,
21.
X = the_answer(5. 6.0);
?
24.
. , ,
,
. unitprice,

? .
25. 3.13. main
using:
using namespace std;
unitprice ?

,
,
~ . .,
, C++.
.
, , .
,
.

, .
,
.
,
, .
.
, ,
.
-
const.
#include .
150 3.

, (
), ,
.
, .

.
/ .



1. 4.0 4.0 8.0
8.0 8.0 1.21
3 3 0
3.0 3.5 3.5
6.0 6.0 5.0
5.0 4.5 4.5
3 3.0 3.0

2. sqrt (>: + ) pow(x. + 7) sqrtCarea + fudge)


sqrtCtime + ticle)/nobody (-b + sqrt(b*b -- 4*a*c)) /(2*a) abs(x - y)
labs(x - y)
fabs(x - y)

3. // 3.14159.
#1nc1ude <1ostream>
#include <cmath> // sqrt M_PI.
using namespace std:

int mainO
{
cout "The square root of " M_PI " is "
sqrt(M_PI) endl;
return 0:
}
4. a ) // ,
// # #include.
finclude <iostream>
using namespace std:

int mainO
{
cout "hello world" endl;
return 0:
}
6 ) // ,
// # include #include.
# include <iostream>
using namespace std;
// .
// .
151

5. Wow
6. :
int sumdnt nl, int 2. 1nt ):
// n l . 2 .

:
int sumdnt nl. int 2. int )
{
return (nl + 2 + ):
}
7. :
double aveCint nl. double 2):
// nl 2.
:
double ave(int nl. double 2)
{
return ((nl + 2)/2.0):
}
8. :
char positive_test(double number):
/ / 'P'. .
/ / 'N*. .

:
char positive_test(double number)
{
if (number > 0)
return 'P':
else
return 'N';
}
9. , , paraml param2.
argl 2.
: argl pa
raml, arg2 param2. .
10. ()
( #include) .
, ,
, , ,
.
. , ,
, .
12. ,
, . ,
.
152 3.

, .
- , .
13. ,
, : ,
, .
,
.
14. , (
, ), , -
' , .
,
.
15. ,
, .
16. ,
.
17. ,
.
18. .
, ,
, ,


.
19. :
double read_f1lter();
// . ,
// >=0. .
:
// iostream.
double read__f1lter();
{
using namespace std;
double value_read:
cout "Enter a number:\n"
cin value__read;
i f (value_read >= 0)
return value_read:
else
return 0.0;
}
20. ,

.
153

21. double,

double ( ).
22. , , 1 nt,
.
,
doubl .
23. , , double,
.
,
doubl .
24. ( , ).
: ,
.
, unltprice
double, ,
1 nt, . ,
,
,
. ,
.
25. unltprice , ,
iostream. main using ,
cin cout iostream
std.


1. ,
, ,
. ,
,
.
,
(1 0,264179 ).
2. ; ,
29 7/8 89 1/2. ,
.
, .
i nt, ,
. ,
.
i nt,
154 3.

, ,
.
doubl .
3. , .
(, -
) .

.
. ,
. double (, 0.053,
5,3 %).
4. ,
.
,
. ,
.
5. , ,
.
, ,
. , ,
, .
while, 2.7 (
). , ^
, ,
.
.
6. ^ ^
/, :

G :
G = 6,673 10-7(*
,

.
.
/^
.
,
.
.
155

7. , ,
, .
,
.
.
3 % (
) 8 % (
).
.
, 35 %, ,
, . ,
35 %
.

.
8. , ,
.
, 2,9
.
( ) , 8
288 1/8
30. ( ,
. 30 39
, 40 1/8 .)
, 5,7 1/10
28. (,
. 29
, 30 1/10 .)
.

.
9. C++
. C++,
,
.
, abs.
int, long, float double.
4

, 3,
.
,
. ,
. , -
, , ,
. , C++,
, .

4 . 1 . void
C++ . ,
3, .
, ,
. C++
, . ,
, , (
) , .
, . ,
, void. ,
, ,
- . ,
, .
void.
4 . 1 . void 157

void
C++ void ,
. , void

.
,
.
void show_results(double f_degrees. double c__degrees)
{
using namespace s t d ;
c o u t . s e t f d o s : -.fixed):
cout.setf(ios:ishowpoint);
cout.precision(l);
cout f_degrees
" degrees Fahrenheit is equivalent to\n" -
c_degrees " degrees Celsius An";
return;

, void
, (
3). -,
void, ,
. -, return
.
void . 4.1.

void _{_);
___


void _{__) - < - -

^
2 ~

_

_J.
__2

return
__

. 4 . 1 . void

void . ,
showresults :
show results(32.5. 0.3);
158 4.

, ,
, .
:
32.5 degrees Fahrenheit 1s equivalent to
0.3 degrees Celsius.
void
, . ,
show_results
. void
(
).
,
. ,
. ,
initialize_screen void :
void initialize_screen()
{
using namespace std;
cout endl;
return;
}

initialize_screen();

,
, .
, ,
. ,
voi d.

:
, 4.1,
,
. :
C = ( 5 / 9 ) ( F - 32)
, 4.1,
Celsius.
4.1. void
//
// .
#include <iostream>

void initialize screenO;


4.1. void 159

// , .
// , .

double cels1us(doub1e fahrenheit);


//
// .

void show_resu1ts (double fdegrees, double cdegrees);


// . , c_degrees (
// ) fdegrees ( ).

int mainO
{
using namespace std:
double f_temperature. c_temperature;
initialize_screen();
cout "I will convert a Fahrenheit temperature"
" to CelsiusAn"
"Enter a temperature in Fahrenheit: ";
cin f_temperature;

c_temperature = celsius(f_temperature);

show_results(f_temperature. c_temperature);
return 0;
}
// iostream:
void in1tialize_screen()
{
using namespace std;
cout endl;
return; // return .
}
double eel si us(double fahrenheit)
{
return ((5.0/9.0)*(fahrenheit - 32)):

// iostream:
void show_results(double f_degrees, double c_degrees)
{
using namespace std:
cout.setf(i OS::fixed);
cout.setf(ios::shovoit):
cout.precision(l);
cout f_degrees
" degrees Fahrenheit is equivalent to\n"
c_degrees " degrees Celsius.Xn":
return; // return .
}

I will convert a Fahrenheit temperature to Celsius.
Enter a temperature in Fahrenheit: 32.5
32.5 degrees Fahrenheit is equivalent to
0.3 degrees Celsius.
160 4.

return void
void, , ,
return.
,
. , ,
, return.
void . ,
,
return.
initialize^screen show^results ,
4.1, return.
,
voi d return, ,
. , ,
. 4.2, . ,
.
( if),
0. ,
, i f.


void ice_cream_division(int number, double total_weight):
// (total_weight)
// (number).
// number 0. .

II iostream:
void ice_cream_division(int number, double total_weight)
{
using namespace std;
double portion:
if (number == 0)
return; // number 0.
// ,
portion = total_weight/number;
cout.setf(ios::fixed);
cout.setf(ios:ishowpoint);
cout.precision(2);
cout "Each one receives "
portion " ounces of ice cream." endl;

. 4.2. return void

, , ,
mai ,
, , . ,
return mai , .
main int, return.
4.1. void 161

void. ,
, .

^


1. :
#1nclude <1ostream>

void friendlyO;
void shydnt aud1ence_count);

int mainO
{
using namespace std:
friendlyO;
shy(6);
cout "One more time:\n";
shy(2):
friendlyO;
cout "End of program An";
return 0;
}
void friendlyO
{
using namespace std;
cout "Hello \n";
}

void shy(int audience_count)


{
using namespace std;
if (audience_count < 5)
return;
cout "Goodbye \n";
}
2. return void?
3. , return ini -
tialize_screen 4.1. ?
? ,
return show_results eel si us?
4. void int,
.
, ,
void.
C++ , return main
, - .
162 4.

5. 1nt ma1n()
void ma1n()? ,
1nt mainO return ?
6. void ?

4.2.

. 3 .
.
.




. ,
,
. , 4.1.
: ,
, .
initial Izescreen, show_
results eel si us.
main :
cout " I will convert Fahrenheit temperature"
" to Celsius.Xn"
"Enter a temperature in Fahrenheit: ";
Gin f_temperature;
,
.
, ,
, .
,
. ,
, ,
.
.
, .
.
,
.
, , ,
-. , ,
.
4.2. 163


, :
(&).
,
, :
void get_input(double& f_var1able)
{
cout "I will convert a Fahrenheit temperature"
" to CelsiusAn"
"Enter a temperature in Fahrenheit: ";
cin f_variable;
}
, ,
get_i nput:
get_input(f_temperature);

f_temperature ,
.
, ,
4.1, .
, ( 4.2).
4 . 2 .
// , .
#1nclude <1ostream>

void get_numbers(1nt& inputl. int& input2);


// , .

void swap_values(1nt& variablel. int& variab1e2):


// variablel var1able2.

void show_results(int outputl. int output2);


// variablel var1able2 .
// .

1nt maInO
{
Int f1rst_num, second_num;

get_numbers(f1rst_num. second_num);
swap_values(f1rst_num. second_num):
show_results(f1rst_num, second_num);
return 0;

// lostream:
void get_numbers(1nt& inputl. int& 1nput2)
{
using namespace std; ^
164 4.

4.2 {)
cout "Enter two integers: ";
cin inputl
1nput2;
}
void swap_values(int& variablel. int& variable2)
{
i n t temp:

temp = variablel:
variablel = variable2:
variable2 = temp:

/ / iostream:
void show_results(int output1. i n t output2)
{
using namespace std:
cout "In reverse order the numbers are: "
outputl " " output2 endl:
}

Enter two integers: 5 10
In reverse order the numbers are: 10 5

:
. getnumbers swapvalues
.
get_numbers(fi rst_num. second_num):
fi rst_num second_num.
:
swap_values(first_num. second_num):


, 4.2.


,
&.
, - .
- ( )
. ,
, -
. ,
, .
, , :
void get_data(int& f i r s t j n , double& second in)
4.2. 165


,
,
.
, , .
,
, . ,
, 4.2, f 1 rstnum
1010, second_nuni 1012.
.
getnumbers
4.2:
void get_numbers(1nt& inputl. 1nt& 1nput2);

inputl 1nput2
, .
:
get_numbers(first_num. second_num);

-,
.
1010
1012

, .
:
first_num 1010 inputl
second_num 1 0 1 2 input2


,
, .
, ,
cin, inputl, ,
, 1010 ( firstnum).
i nput2,
, , 1012 ( secondnum).
,
4.2.
1. , firstnum secondnum
:
first_num
second num^1012
166 4.

( , ,
.
.)
2. (. 4.2) :
get_numbers(f1rst_num. second_num);

3. first num
inputl secondjnum
input2. ,
( C++, , ):
void 1_5(11& ___1010>. 1nt& ___1012)
{
using namespace std;
cout "Enter two integers: ";
cin jio_dapecy_1010
___1012:
)
1010 1012 first_num secondjnum,
,
:
void get_numbers(int& first_num, int& second_num)
{
using namespace std;
cout "Enter two integers: ":
cin first_num
second_num:
}
4. , :
{
using namespace std;
cout "Enter two integers: ";
cin first_num
second_num;
}
5. cin first_nuni secondjnum
, . ( 4.2
fi rst^num 5, secondjnum - 10.)
6. f i rst_num secondjnum
, cin. (
, 4.2, f i rst^num 5,
secondjnum 10.)
, .
first^num 1010, ,
1010, first_num? ,
. ,
get_numbers inputl input2. ,
, 4.2, ,
4.2. 167

, inputl 1nput2,
. ,
1nput2, Inputl. ,
, , 1014
1016. :
int inputl. input2;
get_numbers(input2, inputl): // .
, inputl, ,
inputl, main,
get_nuinbers. inputl,
main, 1014, ,
1014 .
.
inputl input2,
input2 inputl. ,
, inputl input2
input2 inputl.
1016 inputl,
1014 input2.

: swap_values
swapvalues, 4.2,
.
:
void swap_values(int& variablel. int& variable2);
// variablel variable2.
, , ,
first_num 5, second_num 10,
:
swap_values(first_num. seconcl_num);

first^num 10,
second_num 5.
swap_values 4.2 temp.
,
:
void swap__values(int& variablel. int& variable2)
{
variablel = variable2; //
variable2 = variablel;
}
, .
:
swap_values(first_num. second num);
168 4.

f 1 rstnum secondnum
varlablel vdr1able2,
:
f1rst_num = second_num;
second_num = f1rst_num;
, . f1rst_num
secondnum, .
secondnum f 1 rstnum,
, secondnum. (
.) ,
f 1 rstnum secondnum,
, . 4.2
temp. swapvalues
:
temp = f1rst_num:
first_num = second_num;
second_num = temp;


&
. , ,
.



. , .

.
.
( ) ,
.
. ^
^ .

.
, (
).
.
, ,
, -.


. ,
, - :
void good_stuff(1nt& pari. 1nt 2, double& ):
4.2. 169

void,
, . ,
C++ , -.

:

, 4.3,
,
. do_stuff parl_value par2_ref
. -,
.
, parl_value,
.
do_stuff(nl, 2);

parl_value 1. ,
parl_va1ue 1,
1 . ,
parl_value 111,
. - 1
: , , - 1.
, par2_ref, . -
- 2 ( )
par2_ref. :
par2_ref = 222:


2 = 222;

, par2_ref
( 2)
222.
, : ,
,
, &.
.
4.3.
/ /
/ / .
#include <1ostream>

void do_stuff(int parl_value. int& par2_ref);


// parl_value no .
// a par2_ref no .
1nt mainO ^
170 4.

4.3 {)
{
using namespace std;
int nl. 2;

nl = 1;
2 = 2;
do_stuff(nl. 2);
cout "nl after function call = " nl endl:
cout "n2 after function call = " n2 endl;
return 0;
}
void do_stuff(int parl_value. int& par2_ref)
{
using namespace std;
parl_value = 111;
cout "parl_value in function call = "
parl_value endl;
par2_ref = 222;
cout "par2_ref in function call = "
par2_ref endl;
}

parl_value in function call = 111 -
par2_ref in function call = 222
nl after function call = 1
n2 after function call = 222

:
,
, ,
& (
) . -
,
. ,
, ,
, ,
.
, 4.4.
4.2 ,
swapvalues . variablel va-
riable2 .
- f i rst_num secondnum
. variablel variable2
, f i rstnum secondnum .
,
, ,
.
4.2. 171

4.4. ,
/ / ,
/ / .
#1nclude <iostream>

void get_numbers(1nt& Inputl. int& 1nput2):


/ / .

void swap_values(int varlablel. int var1able2); / / .


/ / varlablel variable2.

void show_results(1nt output1. i n t output2);


/ / varlablel. variable2.

i n t mainO
{
i n t first_num. second_num:

get_numbers(first_riuin. second_num);
swap_values(first_nuni. second_num);
show_results(f1rst_num. second_num);
return 0;

void swap_values(1nt variablel. int variable2) // .


{
int temp;

temp = variablel;
variablel = variable2;
variable? = temp;

/ / iostream:
void get_numbers(int& inputl. int& input2)
{
using namespace std;
cout "Enter two integers: ";
cin inputl
1nput2;

void swap_values(int& variablel, int& variable?)


{
int temp;

temp = variablel;
variablel = variable2;
variable2 = temp;
}

/ / iostream:
void show_results(1nt outputl. i n t output2)
{
using namespace std;
cout "In reverse order the numbers are: "
outputl " " output2 endl;
172 4.


Enter two integers: 5 10
In reverse order the numbers are: 5 10


7. :
#include <iostream>
void figure_me_out(int& x. i n t y. int& z);
i n t mainO
{
using namespace std;
int a. b. c;
a = 10;
b = 20;
= 30;
figure_me_out(a. b. c);
cout a " " b " " c;
return 0;

void f1gure_me_out(int& x. i n t y. int& z)


{
using namespace std;
cout X " " " " z endl;
X = 1;
= 2:
z = 3;.
cout X " " " " z endl;

8. , 4.2,
swap^val ues & ?
9. , 4.3,
do_stuff , par2_ref
:
void do_stuff(1nt parl_value. int& par2_ref);

10. zero_both void


int,
.
. add_tax void.
: taxrate, ,
cost, .
cost, .
12. , 1; , ,
?
4.3. 173

4.3.

,
, .

, ,
,
.
.
, .
, .

,
. ,
: , ,
, main.
.
,
.
, ,
, .
,
.
4.5 ,
4.2. 4.2
f 1 rst_num second^num, 4.5

first_num <= seconcl_num

, .
firstnum secondnum,
swapvalues, .
order,
swapvalues. ,
swapvalues
( ),
, .


:
. ,
174 4.

. ,
.
, ,
. ,
.
-, .
, swap_values
4.5 :
void swap_values(1nt8i varlablel. 1nt& var1able2);
// : varlablel var1able2
// .
// : varlablel var1able2
// .

4.5.
// , .
#1nclude <iostream>

void get_1nput(1nt& inputl. 1nt& input2):


// .

void swap_values(1nt8i varlablel. 1nt& var1able2);


// varlablel var1able2.

void order(1nt& nl. 1nt& 2);


// 1 2 .
// 1 <= 2.

void g1ve_results(int output1. 1nt output2):


// varlablel var1able2.
// , outputl <= output2.

1nt ma1n()
(
1nt f1rst_num. second_num;
get_i nput(f1rst_num. second_num);
order(f1rst_num, second_num):
g1ve_results(f1rst_num. second_num);
return 0;
}
// iostream:
void getjnput(1nt& inputl. 1nt& 1nput2)
{
using namespace std;
cout "Enter two integers: ";
cin inputl input2;
}
void swap_values(int& varlablel, int& var1able2)
{
int temp:
temp = variablel;
4.3. 175

varlablel = variab1e2:
variab1e2 - temp;
>
// ,
void orderdntS nl. 1nt& 2)
{
if (1 > 2)
swap_va1ues(nl, 2):
}
// iostream:
void give_results(int output1. i n t output2)
{
using namespace std;
cout "In reverse order the numbers are: "
outputl " " output2 endl;
}

Enter two integers: 10 5
In reverse order the numbers are: 5 10
A Celsius, 4.1,
:
double celsiusCdouble fahrenheit);
// : fahrenheit
// .
// :
// .

,
.

:
// : fahrenheit
// .
//
// .

:
void post_interest(double& balance, double rate);
// : balance
// ; rate
// , 5.
// 5 %.
II : balance
// rate.

, post_interest
.

. .
,
. ,
176 4.

.
,
, .

, , .
.
.

:
, ,
.

Quick-Shop ,
.
. ,
(7 ) , 5 %, 8-
10 %.
, .
,
.


, .

.

, :
;
;
.
. -
]; . ,
, ;
.
void get_1nput(doubles cost. 1nt& turnover);
// : .
// : cost .
// turnover - .
// .

double priceCdouble cost. 1nt turnover);


// : cost .
4.3. 177

// turnover - .
// ;
// .

void g1ve_output(double cost, int turnover, double price);


// ; cost .
// turnover - .
// ; price
// .
// : cost, turnover price
// .

,
:
i n t mainO
{
double wholesale_cost. retail_price;
i n t shelf_time;

introductionO;
getJnput(wholesale_cost. shelf_time);
retail_price = price(wholesale_cost. shelf_time);
give_output(wholesale_cost. shelf_time, retai i_price);
return 0;
}

,
, .
:
.

get input giveoutput
1 cout. price
:
if turnover <= 7
return ( cost + 5 ^ cost);
else
return ( cost + 10 ^ cost);


:
(5 %), (10 %) ,
(7 ), .
, ,
,
:
const double LOW_MARKUP =0.05; /I %
const double HIGH_MARKUP =0.10; // 10 %
const int THRESHOLD = 7; // HIGH_MARKUP .
//
// 7 .
178 4.

price C++:
if (turnover <= THRESHOLD)
return ( cost + (LOW_MARKUP * cost) );
else
return ( cost + (HIGH_MARKUP * cost) ) ;

4.6.
4.6.
/ /
/ / , Quick-Shop.
#1nclucle <iostream>

const double LOW_MARKUP = 0.05; // 5 ^


const double HIGH_MARKUP = 0 . 1 0 ; / / 10 ^
const i n t THRESHOLD = 7; / / HIGH_MARKUP .
/ /
/ / 7 .

void introductionO;
// : .

void get_input(double& cost. int& turnover);


// : .
// : cost ,
// turnover - .
// .

double priceCdouble cost, int turnover);


// : cost .
// turnover - .
// ;
// .

void give_output(double cost, int turnover, double price);


// : cost .
// turnover - .
// ; price
// .
// : cost, turnover price
// .

i n t mainO
{
double wholesale_cost. retail_price;
i n t shelf_tinie;

introductionO;
get_input(wholesale_cost. shelf_time);
retail_price = price(wholesale_cost. shelf_time);
give_output(wholesale_cost, shelf_time, retail_price);
return 0;

/ / iostream:
void introductionO
4.3. 179

{
using namespace std;
cout "This program determines the retail price for\n"
"an item at a Quick-Shop supermarket store.\n";

// iostream:
void get_input(double& cost. int& turnover)
{
using namespace std;
cout "Enter the wholesale cost of item: $";
cin cost;
cout "Enter the expected number of days until sold:
cin turnover;

// iostream:
void give_output(double cost, i n t turnover, double price)
{
using namespace std;
cout.setfCios::fixed);
cout.setf(i OS::showpoi nt);
cout.precision(2);
cout "Wholesale cost = $" cost endl
"Expected time until sold = "
turnover " days" endl
"Retail price = $" price endl;
}
// :
// LOW_MARKUP. HIGH_MARKUP THRESHOLD:
double price(double cost, int turnover)
{
if (turnover <= THRESHOLD)
return (cost + (LOW_MARKUP * cost));
else
return (cost + (HIGH MARKUP * cost));


This program determines the r e t a i l price for
an item at a Quick-Shop supermarket store.
Enter the wholesale cost of item: $1.21
Enter the expected number of days until sold: 5
Wholesale cost = $1.21
Expected time until sold = 5 days
Retail price = $1.27



. : ,
5 %, , 10 %.

.
180 4.

.
, . (
) ,
. , ,
7. ,
7, , ,
7.
, ;,
7 . , ,
,
. ,
6 , ,
8 .


13.
?
14. ?
15. order ,
4.5, .
16. sqrt,
.

4.4.

.


,
. .
,
.
, ?
, . 4.7
getj nput, 4.6.

,
. , , ( ),
,
. ( 4.7) ,
, .
4.4. 181

,
. , , .
, ,
, .

. ,
, .
. ,
get_1 nput
4.7 , .
,
.
, .
, , :
,
, .
, 4.8 g1 ve_out-
put , 4.6. 4.8
Introduction,
( ). price
, .
, , 4.8,
, price .
.

,
.
.

. .
, .
,
. ,
,
,
.
4 , 7 .
/ / g e t j n p u t .
#1nclude <1ostream>

void g e t j n p u t (doubles cost. 1nt& turnover);


// : .
// : cost .
// turnover - .
/ / . i ^
182 4.

4.7 ()
int mainO
(
using namespace std:
double wholesale_cost;
i n t shelf_time;
char ans;

cout.setfCios::fixed);
cout.setf(ios:ishowpoint):
cout.precision(2);
do
{
get_input(wholesale_cost. shelf_time);

cout "Wholesale cost is now $"


wholesale_cost endl:
cout "Days until sold is now "
shelf_time endl :

cout "Test again?"


"(Type for yes or n for no): ";
cin ans;
cout endl;
} while (ans == 'y' || ans == 'Y');

return 0;
}

// iostream:
void get_input(doubles cost. int& turnover)
{
using namespace std;
cout "Enter the wholesale cost of item: $";
cin cost;
cout "Enter the expected number of days until sold:
cin turnover;


Enter the wholesale cost of item: $123.45
Enter the expected number of days until sold: 67
Wholesale cost is now $123.45
Days until sold is now 67
Test again? (Type for yes or n for no):

Enter the wholesale cost of item: $9.05


Enter the expected number of days until sold: 3
Wholesale cost is now $9.05
Days until sold is now 3
Test again? (Type for yes or n for no): n


,
.
4.4. 183

4.8.
//
// , Quick-Shop.
#1nclude <iostream>

void introductionO;
// : .

void get_1nput(doubles cost. 1nt& turnover);


// : .
// : cost .
// turnover - .
// .

double priceCdouble cost. 1nt turnover);


// : cost .
// turnover - .
// ;
// .

void g1ve_output(double cost. 1nt turnover, double price);


// : cost ;
// turnover - .
// ; price
// .
// : cost, turnover price
// .

i n t mainO
{
double wholesale_cost. retail_price;
i n t shelf_time;

introductionO;
get_input(wholesale_cost. shelf_time);
retail_price = price(wholesale_cost. shelf_time);
give_output(wholesale_cost. shelf_time. retail_price);
return 0;

// iostream:
void introductionO // .
{
using namespace std;
cout "This program determines the retail price for\n"
"an item at a Quick-Shop supermarket store.\n";

// iostream:
void get_input(double& cost. int& turnover) // .
{
using namespace std;
cout "Enter the wholesale cost of item: $"; ^
184 4.

4.8 {)
Gin cost;
cout "Enter the expected number of days until sold: ":
cin turnover;
}
// iostream; ,
void g1ve_output(double cost, int turnover, double price)
{
using namespace std;
cout.setfdos::fixed);
cout.setfdos: :showpo1nt);
cout.prec1s1on(2);
cout "Wholesale cost = $" cost endl
"Expected time until sold = "
turnover " days" endl
"Retail price= $" price endl;
}
// .
double price(double cost, int turnover)
{
return 9.99: // , .
}

This program determines the retail price for
an item at a Quick-Shop supermarket store.
Enter the wholesale cost of item: $1.21
Enter the expected number of days until sold: 5
Wholesale cost = $1.21
Expected time until sold = 5 days
Retail price= $9.99


17. .
?
18. ?
19. introduction,
4.8.
20. addtax .
21. ?
22. , .
double in_prob(double pressure, double humidity, double temp);
// ; pressure .
// humidity - .
// temp - .
// 1. ; .
// , 1 - 100 %.
. ,
.
185

,
, void.

. :
.

.
, ;
.

, .
, .
, ,
.

. ,
.
, ,
.
,
.
.
.
(, ,
) .



1. Hello
Goodbye
One more time:
Hello
End of program.

2. , void return.
3. return 1n1t1alize_screen,
4.1, .
, .
return showresults
. return
186 4.

Celsius,
. , initialize_screen show_results
void, Celsius .
4. finclude <iostream>

void product_out(int n l . i n t n2. i n t n3);

int mainO
{
using namespace std;
int numl. num2. num3;
cout "Enter three integers: ";
cin numl num2 num3;
product_out(numl. num2. num3);
return 0;

void product_out(int nl. int n2. int n3)


{
using namespace std;
cout "The product of three numbers "
nl ", " n2 ". and "
n3 " " (1*2*) endl:
return;
}
5. .
6. voi d, ,
. , .
7. 10 20 30
1 2 3
1 20 3

8. Enter two integers: 5 10


In reverse order the numbers are: 5 5
9. parl^value in function call = 111
par2_ref in function call = 222
nl after function call = 1
n2 after function call = 2

10. void zero^both (int& nl, int& n2)


{
nl = 0;
2 = 0;
}
11. void add_tax (double& tax_rate. double& cost)
{
cost = cost + (tax_rate/100.0)*cost;
}
100 . -
lep, 10 % 10/100, 1/10 .
187

12. , , , ,
.
13.
.
14. , .
15. void order(1nt& 1. int& 2);
// : 1 2 .
// : 1 2
// . 1 <= 2.
16. double sqrtCdouble n);
// : n>=0.
// .
17. ,
,
. , , ,
.
18. - ,
.
19. #1nc1ude <1ostream>

void 1ntreduction;
// : .
1nt mainO
{
using namespace std;
introductionO;
cout "End of testAn":
return 0;

// iostream:
void introductionO
{
using namespace std;
cout "This program determines the retail price for\n"
"an item at a Quick-Shop supermarket store.\n";
}
20. // getjnput.
#include <iostream>

void add^tax (double& tax_rate, double& cost);


// : tax_rate .
// cost - .
// : cost ,
// , .

int mainO
{
using namespace std;
double cost, tax rate;
188 4.

char ans;

cout.setfdos::fixed);
cout.setf(1 OS::showpoi nt);
cout.prec1s1on(2);
do
{
cout "Enter cost and tax rate:\n";
cin cost tax_rate:
add_tax(tax_rate. cost);
cout "After call to add_tax \n"
"tax__rate 1s " tax_rate endl
"cost 1s " cost endl;

cout "Test again?"


"(Type for yes or n for no): ";
c1n ans;
cout endl;
} while (ans == "y' !| ans == 'Y');

return 0;
}
void add_tax (doubles tax_rate. double& cost)
{
cost = cost + ( tax_rate/100.0 )*cost;
}
21. - ; ,
.
22. / / .
double ra1n_prob(double pressure, double humidity, double temp)
{
return 0.25; // , .


>% 24- 12-
(, 14:25 2:25).
. :
, . AM
char: '' AM ( ) '' (
). , ,
char, ,
. (
.) ,
, ,
.
,
.
189

(s. - ,
, 5^ s^, s^ s^.
.
, ,
, .
3. , ,
1 99 . ,
86 , :
86 cents can be given as
3 quarter(s) 1 clime(s) and 1 penny(pennles)

25 (quarter), 10 (dime)
1 (penny).
void compute_co1ns(int co1n_value, 1nt& number. 1nt& amountjeft);
/ / : 0 < coin_value < 100: 0 <= amountjeft < 100.
// : number
// co1n_value ,
// amountjeft ;
// amountjeft ,
// 1 , number*co1n_value.
, amount_left 86.
number 3,
amount_left ( 86
75 , 25 ,
):
compute_co1ns(25. number, amountjeft):

,
.
,
%.
4. ,
. : ,
. ,
. (1
0,3048 ( 12 ), 1 100 .)
5. , ,
.
.
6. ( 4 5.)
, .
, :
,
.
1, 2.
if...else.
190 4.

.
4 5. .
,
.
7. ,
.
: , . ,
.
( 1 2,2046 ; 1 1000 , 1
16 .)
8. , ,
.
.
9. ( .)
, 7 8.
, :
,
. 1,
2.
if...else.
.
.
. ,
.
10. ( 6 9.)
, 6 9.
,
. , ,

. , ,
, .
. 1,
2. ,
, if...else.
.
6 9. ,
if...else. if...else
, ,
, if...else. ,
,
. ,
, , . -
, , .
,
.
191

. :
area = -^Jsis - a)(s ~ b)(s - )
, , 5 :
5 = ( + 6 + )/2
void :
,
area perimeter
. . ,
, b .

.
12.
, .

. :
W= 13,12 + 0,6125 * t - 11,37 * v'''^ + 0,3965 * t * v^'""''
V - /, t (t<=10),
W ( ).
, .
, .
, .
5 -

? ~ .

, ,
, , .

,
, .
( ) .
. ,
,
.
,
.
, .
, .
C++
. ,
-.
.

5 . 1 .
-
, , .
-

. ,
, .
5.1. - 193


,
, C++ .
( ). ,
, , , ,
.
, , ,
. 1 (
) cout - (
). ,
#inclucle iostream.
- , 1 cout.
, in_streani,
. ( , .)
- int
:
int the_number:
1n_stream the_number;

, , outstream,
, .
, outstream
thenumber, "thenumber = ":
out_stream "the_number = " the_number endl;

,
-, -
.

-
,
,
, .
.
,
. ,
, . , ,
,
.
,
,
, . ,
,
194 5. -

, , ,
.
, ,
. ,
, .

-
, ,
] , ,
. ; ,

.
. ,
, , , .
, ,
.
, , ,
.
, .
C++ -.
, ,
- -
.
, .
, , .
,
.
,
. ,
, .
, int char.
1 cout ,
, . ()
if stream ( . input file stream),
ofstream ( . output file stream).
Instream ,
out_stream :
ifstream in_stream;
ofstream out_stream;
i fstream ofstream fstream,
, , include
( ):
#include <fstream>
5.1. - 195

, (
),
if stream of stream:
using namespace std;

, ,
instream outstream.
open. ,
instream infile.dat.

i n_stream.open("i nfi1e.dat"):

open . ,
. -,
. -,
. open ,
,
.
, ,
, . ,
.

open, .
, instream,
one_number another_number.
int one_number. another_number;
in_strean one_number another_number:

( ) ,
. ,
out_stream outfile.dat:
ofstream out_stream;
out_stream.open("outfi1e.dat");

, open,
ofstream, . ,
.
out_stream open
. ,
onenumber -
ther_number:
out_stream "one_number = " one_number
" another_number = " another_number;
, ,
. ,
. .
196 5. -

infile.dat outfile.dat..
, ,
, .
,
open.
,
.
, 5.1,
.
, ,
. close.
, 5.1:
in_stream.close():
out_stream.close();

, 1 ose .
, ,
.
, .
.

. ,
. ,
, , , ,
.
,
open. ( ,
, .)
5 . 1 . -
// 1nfile.dat.
// outfile.dat.
// ( 5.2.)
#1nclude <fstream>

int mainO
{
using namespace std;
ifstream in_stream;
ofstream out_stream;
i n_stream.open("1nfi1e.dat");
out_stream.open("outf11e.dat");

int first, second, third;


in_stream f i r s t second third:
out^stream "The sum of the first 3\n"
"numbers in infile.datXn"
"is " (first + second + third)
end!;
5.1. - 197

in_stream.c1ose();
out_stream.close();
return 0;
}

infile.dat outfile.dat
(He ) ( )
The sum of the f i r s t 3
numbers in inf1le.dat
is 6


1n_stream outstream, ,
1 cout, .
, . ,
1n_stream outstream open.
:
ifstream in_stream;
ofstream out_stream;
i n_stream.open("i nf11e.dat");
out_stream.open("outf11e.dat");

?
open, 1n_stream, open,
out_streani, . , ,
, , .
, , .
, .
open, - ,
.
,
, instream outstream. ,
, -. , open
out_stream, instream.
, -
. , open, .
- .
, , -
. , , :
ifstream in_stream, in_stream2;
ofstream out_stream. out_stream2;

TO 1n_stream.open in_stream2.open , -
out_stream.open out_stream2.open.
198 5. -

, -, .
- , ,
- - . ,
1 fstream, of stream - open (
). of stream -
precision, ay ifstream .
precision cout, .
- ,
,
:
i n_s t ream. infile.dat"):
, ,
,
open inflle.dat
in_stream, .
,
, , .

, . ,
, ,
,
. , open
instream.
open , (if-
stream of stream), close. ,
, -
. - i fstream of stream
.


, .
-. , .
( ) , -
.

-

_.__(_):

i n_st earn.open("1nf11.dat"); '
out_stream.open("outfi1e.dat");
out_stream.precision(2);
__ ( ) _.
5.1. - 199

:
,
open ,
. , ,
, , open
. ,
.
open , , ,
, , .

- fail, 1f stream, of stream.
bool.
1n__stream :
1n_stream.fa1l()

,
, while if.. .else.
fail open;
open , fail
true. , open:
in_stream.open("1nfne.dat"):
i f (in_stream.fa1l())
{
cout "Input f i l e opening failedAn":
exit(l); // .
}
;
, fail false
.
fail -,
. , i n s t ream, fail
open instream,
open, ,
.
exit ,
,
.
. ,
#i 1 ude:
#include <cstdlib>
, ,
, exit:
using namespace std;
200 5. -

exit .
,
1, 0. , ,
, ,
.
5.2 , 5.1,
open.
, 5.1. , infile.dat
, 5.1, outfile.dat,
.
- , 5.2
. ,
infile.dat ,
.
5.2. - ,
// 1nf1le.dat.
// outfile.dat.
#1nclude <fstream>
#include <iostream>
#include <cstdlib>

int mainO
{
using namespace std;
ifStream in_stream;
ofstream out_stream:

1n_stream.open("i nfile.dat");
if (in^stream.failO)
{
cout "Input file opening failed.Xn";
exit(l):
}
out_stream.open("outfi1e.dat");
if (out_stream.fail())
{
cout "Output file opening failed.Xn";
exit(l);
}
int f i r s t , second, third;
in_stream f i r s t second third;
out_stream "The sum of the f i r s t 3\n"
"numbers in infile.datXn"
"is " (first + second + third)
end!;

in stream.closeO;
5.1. - 201

out_stream.close();

return 0:
}
, infile.dat
Input f i l e opening failed.
,
, cout.
, #1 1 ude
iostream. ( , #include
<fstreani>, #1nclude <iostream> , ,
,
, .)

exit

exit {_):
. -
_ ,
1 ,
, .
exit cstdllb. ,
, :
#1nclude <cstdl1b>
using namespace std:
, ,
, .

-
, 1
cout, , .
- -
. ,
, , :
cout "Enter the number: ";
cin the_number;
cout "The number you entered Is " the_number:

, ,
, . ,
, ,
. , ,
. 1 n_f 11 ,
202 5. -

,
- -,
:
1n_f1le the_number:

,
.
. ,
, ,
, .
. cin cout,
- ,
, .


1. , ,
f 1 , , fout,
. fin fout?
#1nclude ( )
?
2. , ,
stuff 1 .dat
stuff2.dat. fin
stuff 1 .dat, fout stuff2.dat?
, , .
3. , ,
, ,
stuff1.dat, stuff2.dat. ?
4. , 5.1
, outfile.dat,
. ( - inflle.dat.)
?
5. #1nclude ,
exit?
6. exitd)?
7. , , dobedo - ],
1 nt.
dobedo bla 7?
8. ?
?
5.1. - 203

9. - if stream
.
10. . ,
?
. , ,
?

-
infile.dat,
outfile.dat.
1. #1nclucle:
#1nclude <fstream> // -
#1nclucle <1ostream> // cout
#1nclucle <cstdl1b> // exit
2. (, 1n_stream)
if stream. (,
out_stream) ofstream:
using namespace std;
ifstream in_stream:
ofstream out_stream;
3. - open ,
. - fail,
, open:
i n_stream.open("i nfi1e.dat"):
i f (in_stream.fail())
{
cout "Input file opening failed.Xn";
exit(l):
}
out_stream.open("outfi1e.dat"):
if (out_stream.fail())
{
cout "Output file opening failed.\n";
exit(l);
}
4. instream infile.dat:
in_stream some_variable some_other_variable;
5. out_stream, outfile.dat:
out_stream "some_variable = " some_variable endl;
6. , 1 ose:
in_stream.close();
out_stream.close();
204 5. -


( )
-
open, ofstream.
, open
, (
, ).
,
.
innportant.txt
, :
ofstream outStream;
outStream.open("1mportant.txt". 1os::app):

important.txt , ,
,
. ,
5.3.
open ios: : ,
10St ream. 1 1 ude:
#1nclude <1ostream>

, ,
1 os:: :
using namespace std;

,
.
5.3.
/ / data.txt.
#inclucle <fstream>
#1nclude <iostream>

int ma1n()
{
using namespace std;
cout "Opening data.txt for appending.\n";
ofstream fout;
fout.open("data.txt", 1os::app);
if (fout.failO)
{
cout "Input file opening failed.\n";
exit(l);
}
fout "5 6\n"
"7 8\n";
5.1. - 205

fout.closeO;
cout "End of appending to f 1 l e . \ n " ;

return 0;
}

data.ixt data.txt
( ) ( )

,
Opening data.txt for appending.
End of appending to f i l e .


, ,
.

_.open(_. ios::);

ofstream outStream;
outStream.openCimportant.txt". ios::app);


( )
-
. , open,
:
i n_stream.open("i nfi1.dat");

. , , 5.2,
infile.dat,
outfile.dat.
, infile2.dat, outfile2.dat,
open
. ,
, , ,
.
.
,
10. ,
206 5. -

, .
. ,
:
cout "This is s t r i n g . " ;

, -
open. ,
cout, .
,
, .
:
char file_name[16]:

char ,
,
, .

, .
file_name 15 . file_
name ,
, 16 .
,
. :
cout "Enter the input file name (maximum of 15 characters):\n";
cin file_name;
cout "OK, I w i l l edit the f i l e " file_name endl;

A , :
Enter the input f i l e name (maximum of 15 characters):
myfile.dat
OK. I w i l l edit the f i l e myfile.dat

, f i 1 ename,
- open. ,
i nstream ,
f i 1 e_name ( - fai 1
, ):
ifStream in_stream;
in_stream.open(fi1e_name);
i f (in_stream.fail())
{
cout "Input file opening failed.Xn";
exit(l);
}

: ,
- open, .
5.1. - 207

5.4 ,
5.2. ,
.
1 n_f 11 e_natne out_f 11 e_name,
open.

.
, ,
.
5.4.
// .
// .
#include <fstream>
#1nclude <1ostream>
#1nclude <cstdlib>

int mainO
{
using namespace std;
char in_file_name[16], out_fne_name[163;
ifstream 1n_stream;
ofstream out_stream;
cout "I will sum three numbers taken from an input\n"
"file and write the sum to an output file.Vn";
cout "Enter the Input file name (maximum of 15 characters):\n";
cin in_fne_name;
cout "Enter the output file name (maximum of 15 characters):\n";
c1n out_fi1e_name:
cout "I will read numbers from the file "
in_file_name " and\n"
"place the sum In the f i l e "
out_fne_name endl;

1n_st ream, open (in_fne_name):


1f (1n_stream.fa1l())
{
cout "Input f i l e opening fa11ed.\n":
ex1t(l);

out_st ream, open (out_file__nanie) ;


1f (out_strearn.fan())
{
cout "Output file opening failed.\n":
exlt(l);
}
Int first, second, third;
1n_stream f i r s t second third:
out_stream "The sum of the first 3\n"
"numbers 1n " in_fne_name endl
"Is " ( f i r s t + second + t h i r d )
endl; ^
208 5. -

5.4 ()
in_stream.c'Iose();
out_streani.close();

cout "End of program.\n"


return 0;

numbers,dot outfile.dat
(He ) ( )
The sum of the f i r s t 3
numbers in i n f i l e . d a t
is 6

,
I win sum three numbers taken from an input
file and write the sum to an output file.
Enter the input file name (maximum of 15 characters):
numbers.dat
Enter the output file name (maximum of 15 characters):
sum.dat
I will read numbers from the file numbers.dat and
place the sum in the file sum.dat
End of program.

5.2.

-
, .




. C++ ,
,
.
,
( )
. ,
:
cout.setfdos: :fiXEd):
cout. setf (10S:: showpoi nt) ;
cout.precis1on(2);
5.2. - 209

, ,
.
,
. ,
outstream,
,
.
out^stream.setfdos: :f1XEd);
out_stream. setf ( i o s : : showpoi n t ) ;
out_streani. precision (2);

.
- preci si on. ,
outstream,
.
, ,
.
, :
23. 2.27 2.2 6.9-1 0.00069
,
:
23.56 2.267 2.21 0.69 0.69-4

.
precision .
- , out_stream_two,
out_stream.precision out_stream,
out_streani_two. precision
, ,
:
out_streani_two.precision(3);


precision. setf
out_stream:
out_stream.setf(ios: :fixed);
out_streani. setf ( i os:: showpoi n t ) ;

. setflags- .
- .
setf,
, .
setf ,
: ios:: fixed ios:: showpoi nt. ,
doubl ,
210 5. -

, .
setf , (,
doubl ) ,
.
1 OS:: showpoi nt ,
. , 2.0
, 2. ,
, . 5.1
.
5 . 1 . setf


1os::fixed He
(
ios::scientific)
1os::scientific He
(
i os:: f i xed)
i os:: f i xed
i os:: sci enti fi ,
,
ios::showpoint

. ,


ios:ishowpos

ios::right - wi dth,
,

.
.
(
ios:: left.)
ios::left - wi dth,
,

.
.
(
ios:: right.)

i os:: showpos. , -
:
cout,setf(i OS::showpos);

TO .
5.2. - 211

,
.
width.
, cout:
COut "";
cout.w1dth(4):
cout 2 endl:

:
2

2 . w1 dth
, .
( 2) , width
, 2
. ,
width, ,
.
width
. ,
, wi dth .
, setw, .
unsetf.
, :
cout.unsetf(i OS::showpos);


setf, ios: :showpoint, ,
i os:: ?
-, .
: , -
, -,
( ).
setf , 5.1, ,
, .
i os:: . ,
, showpoint fixed,
ios. :: .

,
,
212 5. -

.
-. ,
. ,
. , endl, ,
.
- setw setprecision.
setw - width
. setw,
, . ,
cout "Start" setw(4) 10
setw(4) 20 setw(6) 30;
:
Start 10 20 30
( 10 , 20 - ,
30 - .)
setprecision - precision (
). ,
setw. ,
setprecision :
out_stream.setf(ios: :fiXEd):
out_stream.setf(ios::showpoint):
cout "$" setprecision(2) 10.3 endl
"$" 20.5 endl;

:
$10.30
$20.50


setprecision, ,
setprecision precision.
(, precision.)
setw set-
precision, :
#include <iomanip>

using namespace std;


12. (
#i ncl ude):
cout "*";
cout.w1dth(5):
cout 123
5.2. - 213

"*" 123 "*" endl:


cout "*" setw(5) 123
"*" 123 "*" endl;
13. (
#1nclude):
cout "*" setw(5) 123;
cout.setfCios:: left):
cout "*" setw(5) 123;
cout.setfdos:: right);
cout "*" setw(5) 123 "*" endl;
14. (
#1nclude):
cout "*" setw(5) 123 "*"
123 "*" endl;
cout.setf(10S::showpos);
cout "*" setw(5) 123 "*"
123 "*" endl;
cout.unsetf(1 OS::showpos);
cout.setfdos: :left):
cout "*" setw(5) 123 "*"
setw(5) 123 "*" endl;
15. stuff.dat
(
#1nclude):
ofstream fout:
fout.open("stuff.dat");
fout "*" setw(5) 123 "*"
123 "*" endl:
fout.setf(i OS::showpos):
fout "*" setw(5) 123 "*"
123 "*" endl;
fout.unsetf(i OS::showpos);
fout.setf(ios:: left);
fout "*" setw(5) 123 "*"
setw(5) 123 "*" endl;
16. (
#1 1 ude):
cout "*" setw(3) 12345 "*" endl;
17.
- setf :
) ios::fixed;
) ios::scientific;
) ios::showpoint;
) ios::showpos;
) ios::right;
) ios::left.
?
214 5. -

18. lnfile.dat
outfile.dat:
// .
// .
#1nclucle <fstream>
int mainO
{
using namespace std;
ifstream instream;
ofstream outstream;
instream.openC"1nf1le.dat");
outstream.open("outf11e.dat");

1nt first, second, third;


in_stream first second third;
out_stream "The sum of the first 3\n"
"numbers in infile.datVn"
"is " (first + second + third)
endl;

instream.closeO;
outstream.closeO;

return 0;
}
, ,
? ( - .)


.
, . , make_neat,
5.5, :
Ifstream ofstream .
5.5.
// .
// rawdata.dat,
// neat.dat .
#1nclude <1ostream>
#include <fstream>
#1nclude <cstdlib>
#inc1ude <iomanip> // setw.
using namespace std;
// .
void make_neat(ifstream& messy_file. ofstream& neat_file.
int number_after_decima1 point, int field_width);
// : messy_file neat_file
// open.
// : messy_file
// , neat_file.
//
// ( ):
5.2. - 215

// number_after_dec11 point
// :
// ,
// field_width.
// ( .)

int mainO
{
ifstream fin;
ofStream fout:
fi n.open("rawdata.dat"):
if (fin.failO)
{
cout "Input file opening failed.Xn";
exit(l);

fout.open("neat.dat");
if (fout.failO)
{
cout "Output file opening failed.Xn";
exit(l);

make_neat(fin, fout, 5, 12);

fin.closeO:
fout.closeO;

cout "End of program.\n";


return 0;
}
// iostream. fstream iomanip.
void make_neat(ifstreams messy_file, ofstream& neat_file.
int number_after_decimalpoint, int field_width)
{
neat_file.setf(iOS::fixed): // He .
neat_file.setf(ios::showpoint): // .
neat_file.setf(ios::showpos): // .
neat_fne.precision(number_after_decimalpoint):
cout.setf(ios::f1XEd):
cout.setf(1 OS::showpoi nt);
cout. setf (1 OS:: shovos);
cout.precision(number_after_decimalpoint);

double next;
while (messy_fne next) // ,
{
cout setw(field_w1dth) next end!:
neat_file setw(fie1d_w1dth) next endl:
}
216 5. -

rawdata.dat neat, dot


( ) ( )
10.37 -9.89897 +10.37000
2.313 -8.950 15.0 -9.89897
+2.31300
7.33333 92.8765 -8.95000
-1.2375684322 +15.00000
+7.33333
+92.87650
-123.75684

,
+10.37000
-9.89897
+2.31300
-8.95000
+15.00000
+7.33333
+92.87650
-123.75684
End of program.

:
, .

,
. ,
,
, .
,
. , , ,
1n_stream.
:
double next, sum = 0:
int count = 0:
while (B .)
{
1n_stream next;
sum = sum + next;
count++;
}
= sum/count.
C++,
:
( .)
5.2. - 217

, :
(in_stream next)

:
double next, sum = 0;
int count = 0:
while (in_stream next)
{
sum = sum + next;
count++:
}
= sum/count.
, , .
Instream next ,
.
tn_stream next
1 n_stream, whi 1 .
, , ,
. ,
true false.
,
, .
,
, . next
doubl ,
, int char.



using. , ,
? , 5.5
, std,
using . using
#1nclude,
5.5.
using
, ,
.
,
std\ 9 .
^ std
, ,
. .
218 5. -

using
.
using namespace std;

, , std
( ), 5.3.
4.11. , ,
,
using namespace std -
. using std
,
.
using
( ).
, ,
, .
,

. ,
, , .

:
, 5.5, rawdata.dat
neat.dat .
, ;
.
(),
.
.
, , ,
. makeneat,
,
.

19. (
#1 1 ude)
:
ifstream ins:
ins.openC'list.clat");
int count = 0, next;
while (ins next)
{
count++;
cout next endl;
5.3. - 219

ins.closeO:
cout count:
, list.dat : 1, 2, 3?
20. void to_screen.
f1le_stream if stream.
:
// : fi1e_stream
// - open.
// ( ).
// : ,
// file_stream.
// . ( .)

21. (
.) ,
,
, , :
#include <iostream>
using namespace std:
// ...
char name[21]:
cout name:
,
name?

5.3. -
: , ?
: , , .

. ,
10,
' 1' ' '. , 10,
' , ' '. ,
: 10 ,
. ,
' '', 10.
,
, .
. +-
,
.
, .
,
.
220 5. -

- get put
get
char. ,
, .
- get cin,
.
1 ,
. ,
(,
), . , get
.
, ,
.
- get ,
char. , .

: nextsymbol.
char next_symbol;
1n.get(next_symbol):

, .
, ,
next_symbol ,
. *\', ,
, 1 . get
next_synibol '\'.
'\', C++
. ,
:
char 1. 2. ;
cin.get(cl);
c1n.get(c2);
cin.get(c3):

, ,
:

CD

, Enter, CD
Enter. , , 1
' ', 2 ' '.
. , .
, -
get, , .
5.3. - 221

'\',
, ' '.
get , ,
. ,
( ' \').
, .
,
, .
cout "Enter line of input and I will echo it:\n"
char symbol;
do
{
cln.get(symbol):
cout symbol;
} while (symbol != '\n');
cout "That's all for this demonstration.";

, .
, :
Enter line of input and I will echo it:
Do Be Do 1 2 34
Do Be Do 1 2 34
That's all for this demonstration.
, '\' ,
. That's all for this demonstration,
.
- -, put,
get , , .
. ,
char, .
put . ,
:
cout.put('a');

ci . get, cout. put


,
.
cin.get cout.put

#include <iostream>

cin cout.
, get
put,

#include <fstream>
222 5. -

' "\"
, '\' "\"
. , cout
, . ' \'
char . "\"
, ;
char.
#1nclude

using namespace std;

- get
- get,
. get
, . ,
, .
, char (-
_). get
.

_.get(_):


char next_symbol:
1 . get (next_syTTibol);

get ,
1 . ,
in_stream,
1n_stream.get(next_symbol);

next_symbol char.
get ,
open.

- putback
( )
,
. ,
, .
,
, , ,
, .
5.3. - 223

-
.
putback,
.
char .
, char.
, ,
fin, , fout,
, :
fln.get(next):
while (next != ' ')
{
fout.put(next);
fin.get(next);
}
fin.putback(next);

f i n, , , .
, putback ,
put .
, putback ,
. ,
. ,
putback,
,
, , .

- put
- put. ,
char.
{_char) .

_.put(j:hdr);


cout.put(next_symbol);
cout.put('a');
put ,
cout . ,
out_stream,
out_streain.put('Z');
Z , .
put ,
open.
224 5. -

:
, .
, ,
. 5.6
get_1 nt, ,
, , . ,
, ,
( )
, .
newl 1 ,
, .
. No,
( N),
newl 1 , .
75, 75,
, No. new_l 1 ,
75, .
, ,
do...wh1le getjnt.
No ( ),
. ,
N,
Y (
, ).
Yes No , ,
. -
,
Yes,
. ,
No , ( N
), ,
Y', No ,
.
, Yes
-, Y, ?
. ,
- , , .
,
, .
5.6.
/ / , newjine g e t j n p u t .
#1nclude <1ostream>
using namespace std;
void new l i n e O ;
5.3. - 225

// .
// '\'.
// .

void get_1nt(int& number);


// : number
// .

1nt mainO
{
1nt n;
get_int(n);
cout "Final value read in = " n endl
"End of demonstration.\n";
return 0;

// iostream.
void newJineO
{
char symbol:
do
{
cin.get(symbol):
} while (symbol != '\n');
}
// iostream.
void get_int(int& number)
{
char ans;
do
{
cout "Enter input number: ";
cin number;
cout "You entered " number
"Is that correct? (yes/no): ";
cin ans;
newJineO;
} while ((ans != 'Y') && (ans != 'y'));
}

Enter input number: 57
You entered 57 Is that correct? (yes/no): No
Enter input number: 75
You entered 75 Is that correct? (yes/no): yes
Final value read in = 75
End of demonstration.

: *\n'
- get ,
, .
226 5. -


'\', . (
), ; -
get
'\'.
newline, 5.6.
.
cin.
, :
cout "Enter 'number:\n";
1nt number;
cin number;
cout "Now enter a l e t t e r : \ n " ;
char symbol;
cln.get(symbol);

.
, :
Enter number:
21
Now enter a letter:
A

number , , 21.
, symbol , .
\. 21
'\' 1 . get (symbol). ,
get . (
, , ,
. ,
symbol ' \',
, , ,
.)
, number
21, symbol ''. :
cout "Enter number:\";
1nt number;
cin number;
cout "Now enter a letter:\n";
char symbol;
cin symbol;
new_l 1 ,
5.6:
cout "Enter number:\";
int number;
cin number;
new lineO;
5.3. - 227

cout "Now enter a letter:\n";


char symbol;
c1 n.get(symbol);
,
1, .

22. , char.
:
cin ;

cin.get(c);

23. , char.
:
cout ;

cout.put();

24. ( , putback.)
- putback .

? ,
' ', putback ' b' ?
25. ( ,
, ):
char 1. 1, . 4;
cout "Enter line of 1nput:\n":
cin.get(cl);
c1n.get(c2):
cin.get(c3);
cin.get(c4):
cout cl c2 c3 c4 "END OF OUTPUT";

:
Enter line of input:
a b d e f g
?
26. ( ,
, ):
char next;
int count = 0 ;
cout "Enter a line of input:\n";
cin.get(next);
while (next != '\n*)
{
if ((count^2) == 0) // true, count .
228 5. -

cout next;
count++;
cln.get(next):

:
Enter line of input:
abcdef gh
?
27. , , 26.
:
Enter line of input:
0 1 2 3 4 5 6 7 8 9 10 11
, ?
28. ( ,
, ):
char next;
int count = 0:
cout "Enter a line of input:\n";
cin next;
while (next != '\n')
{
if ((count^2) == 0) // , count .
cout next;
count++;
cin next;
}

Enter a line of input
0 1 2 3 4 5 6 7 8 9 10 11

, ?

- eof
- eof,
,
.
eof . end of file
. , ,
, f i n, eof :
fin.eof
,
while, do...while if...else. ,
, ;
, .
5.3. - 229

, , ,
eof (!).
:
i f (Ifm.eofO)
cout "Not done yet.":
else
cout "End of the file.";

1 f ,
f 1 . , ,
f 1 , :
Not done y e t .

, :
End of the f i l e .

, instream
open.
while:
in_stream.get(next);
while (! in_stream.eof())
{
cout next; // ,
// cout.put(next).
in_stream.get(next);
}
while no next char
. ,
in_stream.eof() true.
(! in_stream.eof())

false .
, instream.eofO true ,
, .
, (
):

:
< '\'>

' ',
'' , '\',
' '.
, instream.eofO - false
, .
instream. get (next) .
230 5. -

,
.
.
. -
eof true .
while
, .
, ,
(, , ).
.
eof ,
.
.
eof,
: . ,
.
, : eof
,
- get,
.


29. , 1ns ,
- open. ,
. true false
1ns. eof ?
30. void text_to_screen
fllestream If stream.
:
// : f1le_stream
// - open.
// : , f1le_stream.
// .
// ( .)

:
( 5.7)
.
-
. ,

C++. ,

C++. ,
5.3. - 231

,
C++.
cad.dat, - cplusad.dat.
,
"C++". ,
.
,
. '\'
, ,
- get
. get,
, ,
,
.
- eof,
.
5.7.
// cplusad.dat.
// cad.dat ' .
// 'C++'.
// , . .
// cad.dat
// .

#include <fstream>
#1nclude <iostream>
#1nclude <cstdlib>
using namespace std;

void add_plus_plus(ifstream& in_stream. ofstream& out_stream);


// : in_streani cad.dat
// open.
// out_stream cplusad.dat open.
// : , in_stream.
// , out_stream,
// ' "C++".
// ( .)

i n t mainO
{
ifstream f i n ;
ofstream fout;

cout "Begin editing f i l e s . \ n " :

fin.open("cad.dat");
if (fin.failO)
{
cout "Input f i l e opening f a i l e d . \ n " ;
exit(l);
} ^
232 5. -

5.7 ()
fout.open("cplus ad.dat"):
i f (fout.failO)
{
cout "Output f i l e opening failed.Xn"
exit(l):

add_plus_plus(fi n, fout):

fin.closeO:
fout.closeO:

cout "End of editing f i l e s A n " ;


return 0;
}

void add_plus_plus(ifstream& in_stream, ofstream& outstream)


{ "
char next:

in_stream.get(next);
while (! instream.eofO)
{
i f (next = ' O
out_streani "C++"
else
out_streani next;

in_stream.get(next);

cad.dat cplusad,dat
(He ) ( )
is one of the world s most modern C++ is one of the world's most modern
programming languages There 1s no programming languages. There is no
language as versatile as C. and language as versatile as C++, and C++
is fun to use. is fun to use.

,
Begin editing f i l e s .
End of editing f i l e s .



.
toupper. , toupper('a') ''. toupper
, ,
, toupper(' ') ' '.
, to lower,
.
5.3. - 233

toupper tolower cctype,


, ,
linclude:
finclude <cctype>

5.9
cctype.

5.2. ,
cctype

toupper (_11) , char = toupper('a');
cout ;
:
_,


tolower(BbipaMeHMe_char) , char = tolower('A');
cout ;
:
_,


15(_11) true, 1f (1 supper())
cout " 1s uppercase.";
_ else
cout " 1s not uppercase.

;
false
1$1\/(_) true, char = 'a';
If (Islower(c))
_ cout " Is lowercase.
: a Is lowercase.
;
false
i salpha(_) true, char = '$';
If (Isalpha(c))
_11 cout " 1s a letter.";
; else
cout " Is not a letter.
: $ 1s not a letter.
false
1511(_) true, 1f (1sd1g1t('3'))
cout " I t ' s a d i g i t . " ;
_ else
cout " I t ' s not a d1g1t.";
9; : I t ' s a d i g i t .

false
i^
234 5. -

5.2 {)

18$(_) true, i f (isspaceC '))
cout "It's a space symbol.":
_ else
cout "It's not a space symbol.";
, : It's not a space symbol.

;

false

isspace true,
( , ): ,
. isspace
, false. , is
spaceC ') true, isspaceC ') false.
, ,
, ' -' :
char next;
do

cln.get(next);
if (isspace(next)) // , next .
cout '-';
else
cout next;
} while (next != ' . ' ) ;
,
Ahh do be do.

OH :
Ahh-do-be-do.

: toupper tolower
int
C++ int.
, char
, ,
. char
, int.
i nt char (
, ). , char
, .
char
.
cctype . , toupper tolower
5.4. 235

1nt, char; ,
, ,
, . ,
:
cout toupper('a'):
, toupper
tolower, , , ,
char.
char. :
char = toupper('a'); // .
cout ;
,
toupper tolower, char:
cout stat1c_cast<char>(toupper('a')); // .


31. ( ,
, ):
cout "Enter line of 1nput:\n";
char next:
do
{
cln.get(next):
cout next:
} while ((! 1sd1g1t(next)) && (next != '\n')):
cout "<END OF INPUT";
:
Enter line of input:
m see you at 10:30 AM.
?
32. C++, ,
, .

5.4.
C++ . ,

, ,
. ,
, - open close. 1
,
, - open close.
if stream, ,
- open close.
236 5. -


. ,
,
.


, ,
, -, ,
. (, 1, cout,
) - ,
(, if stream of stream) - . ,
.
cin,
, . ,
.
,
- open, cin . ,
,
if stream, cin, , i stream
( f). if stream i stream - ,
, : if stream i stream.
, .
, sour-
ce_f i 1 :
void twQ_sum(ifstreams source_file)
{
i n t n l . n2:
source_file nl n2;
cout nl " + " n2 " = " (nl + n2) encll;
}
, ;
:
i f stream f i n ;

f i n open,
twosum
. twosum :
two_sum(fin);

, ,
, .
, ,
twosum, cin:
two sum(cin); / /
5.4. 237

,
. cin if stream,
twosum, i stream.
twosum, 1 stream,
1f stream. twosum cin :
void better_two_sum(1 streams source_f"ile)
{
int nl. n2;
source_file nl n2:
cout nl " + " n2 " = " (nl + n2) endl;
}
3a bettertwosum twosum .
cin better_two_sum,
:
better_two_sum(cin):
: better_two_sum
, 1.
; :
better_two_sum(f1):
.
, , , f 1
if stream, better__two_sum i stream,
, f i n .
,
: if stream i stream.
, , ,

. , ,
if stream ,
, i stream. ,
if stream open. cin
i stream i fstream,
open.
if stream i stream,
, i stream.
,
i stream .
cin, , .
,
. ,
. ,
.
, , ; :
( ,
open). if stream
238 5. -

1 stream,
. ,
,
(, 1).

. ,
, -
. -
. ,
,
.
.
, ,
. ; eni;e
,
, .


,
, cin,
, 1 stream.
, 1 stream,
if stream.
,'
, cout,
, est ream.
, est ream,
of stream.
, , i stream ostream
, .
.

: 1 stream
if stream. .
ostream,
cout. ofstream,
ostream. Hello ,
:
void say_hello(ostream& any_out_stream)
{
any_out_stream "Hello";
}
Hel 1 ,
aflle.dat:
ofstream fout;
fout.open("aflle.dat");
5.4. 239

say_hello(cout);
say_he1lo(fout);
, of stream
ostream.

: newjine
,
, newl 1 ,
5.6. ,
1, .
1 stream,
:
// iostream:
void new_l1ne(&istream 1n_stream)
{
char symbol;
do
{
in_stream.get(symbol);
} while (symbol != ' \ n ' ) :
}
, .
f 1 ,
new_l1ne(f1n):
.
,
,
new_line(cin);
cin .

new_l 1 , ,
, ,
. C++
new_l 1 : ,
5.6, - ,
. , new_l 1 ,
:
newJ1ne(c1n);

newJineO;
newl 1 ,
.

, .
240 5. -

,
( )
new_l1ne,
, .
, .
// iostream:
void new_l1ne(&istream 1n_stream = c1n)
{
char symbol;
do
{
1n_stream.get(symbol);
} while (symbol != ' \ n ' ) ;
}
:
newJineO;

1 .
:
new_l1ne(f1n);

f 1 .

.
,
, ,
.
, ,
. ,
, ,
. :
// .
// .
// iostream.
void default_args(1nt argl. int arg2. int = -3.
int arg4 = -4)
{
cout argl ' ' arg2 ' ' argS ' ' arg4
endl;
}
, . ,

default_args(5. 6);

,
. :
5 6-3-4
5.4. 241

:
default_args(6. 7. 8);

, ,
, .
:
6 7 8-4


default_args(5, . 7. 8);

, :
5 6 7 8


33. 1? cout?
34. copychar,
.
.
Gin, (
,
). ,
copychar stuff.dat,
, :
ifstream fin;
fin.open("stuff.dat");
copy_char(fin);
copy_char(cin);

35. copyline,
.
.
1, (
,
). ,
stuff.dat, ,
:
1fstream fin;
f1n.open("stuff.dat"):
copyjlne(fin):
copy_l1ne(cin):

36. sendline,
.
, .
cout, (
,
242 5. -

). ,
sendjine
morestuff.dat,
:
ofStream fout;
fout.open("morestuff.dat");
cout "Enter 2 lines of 1nput:\n";
sendjine (fout);
sendjine (cout);
37. ( , ,
.)
void func(double . double = 1.1. double z = 2.3)
{
cout X " " " " z endl;
}

func(2.0);
func(2.0. 3.0);
func(2.0. 3.0, 4.0);
38. ( , ,
.) , ;
,
, .

if stream
- open. .
of St ream , -
open. .
open
- fail.
- , .
-. ,
. ,
i f stream o f stream.

- :
. __ (_);
- precision - cout:
cout.precision(2);
- ,
width, setf precision.
cout, ,
.
243

- get,
. ,
, .
- put,
.
- eof, ,
. ,

, .
,
, .
1 fstream,
ofstream. ( .)
1 stream,
cin,
1f stream. ostream,
cout,
ofstream.

,
. ,
, ,
. , ,
,
.



1. fin fout :
ifStream f i n ;
ofstream fout:

#include:
#inclucle <fstream>
,
using namespace std;
2. fin.open("stuffl.dat");
i f (fin.failO)
{
cout "Input f i l e opening failed An";
exit(l);
}
fout.open("stuff2.dat");
244 5. -

if (fout.failO)
{
cout "Output f i l e opening f a i l e d A n " ;
exit(l):
}
3. f i n . c l o s e O :
fout.closeO;

4. outstream cout.
, cout ,
open
close.
5. #include <cstdlib>
, :
using namespace std:

6. exit .
1
, .
7. bla.dobedo (7);

8. , ,
,
. ,
,
. ,
, . ,
, .
9. - open, close fail.
:
i n t ;
i f stream i n ;
of stream out;
in.openC'in.dat"):
i f (in.failO)
{
cout "Input f i l e opening f a i l e d A n " :
exit(l);
}
in c;

out.open("out.dat");
i f (out.failO)
{
cout "Output f i l e opening f a i l e d A n " ;
exit(l);
}
out c;

in.closeO;
out.closeO;
245

10. .
. ;
.
11. .
,
open,
. ( 1 fstream
of St ream).
,
12. * 123*123*
* 123*123*
. ,
width setw
.
13. * 123*123 * 123*
.
14. * 123*123*
* +123*+123*
*123 *123 *
* + ,
.
15. stuff.dat , 14.
16. *12345*
, ,
, setw.
17. ) ios::fixed.
ios::scien
tific;
) ios::scientific.
()
i OS:: f i xed;
) ios: :showpoint.
;
) ios: :showpos.
;
) ios::right.
, -
width.
, .
i OS:: 1 eft;
) ios: :left. ^
, - width.
246 5. -

,
.
ios::right.
18. outstream cout
, open dose, cout
, . #include <fstream>

iostream, #1nclude
<iostream>.
19. 1
2
3
3

20. void to_screen (1fstream& file_stream)


{
int next;
while (file_streain next)
cout next endl:
}
21. ,
, .
20.
22.
Gin :
, ,
cin.get(c);
,
.
23. . .
24. , - putback,
.
,
putback , . (
, ,
.)
25. , :
Enter l i n e of input:
b df g
a b END OF OUTPUT

26. Bee , :
Enter l i n e of input:
abcdef gh
ace h
247

,
, .
27. , :
Enter line of input:
0 1 2 3 4 5 6 7 8 9 10 11
01234567891 1
, 10 1.
, cin.get , ,
10 , 1 0.
, . ,
,
1, .
28. , ,
. (next != '\')
, next
1 next;
'\' ( ,
). , ,
:
Enter line of input:
0 1 2 3 4 5 6 7 8 9 10 11
0246811

, 27
cin.get, ,
; ,
, . , ,
,
(
9). ,
,
10 .
29. false. true,

( ).
30. void text_to_$creen(ifstreams file__stream)
{
char next:
file_stream.get(next);
while (! file_stream.eof())
{
cout next;
fi1e^strearn.get(next);
}
}
cout next cout. put (next).
248 5. -

31. , :
Enter line of input:
I'll see you at 10:30 AM.
I'll see you at 1<END OF OUTPUT

32. cout "Enter a line of 1nput:\n";


char next:
do
{
cin.get(next):
if (!isupper(next))
cout next:
} while (next != '\n'):
,
!i supper (next), 1 slower (next),
false, next ,
(, ).
33. cin 1 stream, cout ostream.
34. void copy_char(istream& source_file)
{
char next:
source_file.get(next):
cout next:
}
35. void copy_line(istreams source_file)
{
char next:
do
{
source_fi1e.get(next):
cout next:
} while (next != '\n'):
}
36. void sendJine(ostream& target_stream)
{
char next:
do
{
cin.get(next):
target_streaiT] next:
} while (next != ' \ n ' ) :
)
37. 2.0 1.1 2.3
2.0 3.0 2.3
2.0 3.0 4.0

38. :
void func(double x)
{
double = 1.1:
double z = 2.3:
249

cout X " " " " Z end!:


}
void func(doub1e x, double y)
{
double z = 2.3;
cout X " " " " 2 endl;
}
void func(double x, double y. double z)
{
cout X " " " " z endl;
}


1. , 1 nt
. ,
, .
2. , doubl
. ,
, .
3. , ,
double. -
. ,
, . -

:
(Wj - of, (2 - of, { - of . .
: ^, ^, . .
.
, ,
.
4. ,
. ,
, .
, , ,
. ,
.
.
,
.
Enter.
,
'\', .
5. ,
. ,
250 5. -


.
, ;
.
6. , ,
, ; .
1 nt,
. ,
.
7. ,
. , .
,
#N#. )^
, #N#
. .
, ,
#N#,
. ,
. .
,
.

:
#N#
. ,
, , . .,
.
8. ,
. ,
. , , ,
.
, .
.
,
double,
.
,
( , ).
9. , 8, :
)
. ( , ,
.)
, 10,
;
251

) , ,
.
,
;
)
,
.
,
.
10. , (
) , .
,
: , , ,
. ,
.
1 ,
.
. , C++,
. ,
, ,
, 1 cout. :
1

:
1
:
cout
:
cout
, cin
, cout
.
* , 1 ,
cout .
,
. ,
.
. ,
, .
12. ,
. (
252 5. -

.)
:
I'm not sure, but I think you will find the answer In chapter #N.
That's a good question.
If I were you, I would not worry about such things.
That question has puzzled philosophers for centuries.
I don't know. I'm just a machine.
Think about It and the answer will come to you.
I used to know the answer to that question, but I've forgotten 1t.
The answer can be found In a secret place In the woods.

( ),
, .
, ,
.
,
#N 1 17.
17 ,
, 17 1.
,
17. const
NUMBER_OF_CHAPTERS 17.
. new_l 1 , .
13. ,
. ,
count,
count^ANSWERS.
, - 1, - 2 . . ANSWERS
,
:
const 1nt ANSWERS = 8;
, ,
.
:
I'm not sure, but I think you w i l l find the answer In chapter #N.

#N ,
count^NUMBER_OF_CHAPTERS + 1

count ~ , NUMBER_OF_CHAPTERS -
, .
14. , .

, .
, .
, .
253

. ,
.

.

, . ,
,
72 .
15. ,
: , ,
, ,
, .
6

: :
, , ...

5 , ,
. .
,
1 nt, char, 1 f stream . . ,
.
,

.
, .
, , ,
, .

6 . 1 .
5, , -
, , .
,
-.
, , -
.
.



. .
6.1. 255

CD (Certificate of Deposit). ,
.
: , ,
, .
double,
1nt. 6.1
CDAccount, .
. ,
CD,
12 . ,
. :
struct CDAccount
{
double balance;
double 1nterest_rate:
int term; // .
}:
struct , .
CDAccount .
, .
C++ ,
, . ,
, .
,
.
(
).
.
6 . 1 .
/ / , CDAccount.
#inc1ude <1ostream>
using namespace std:

/ / ,
struct CDAccount
{
double balance:
double 1nterest_rate;
int term; // .
}:
void get_data(CDAccount& the_account);
// : the_account.balance
// the_account.interest_rate .
// .

int mainO
{
CDAccount account: ^
256 6;

6.1 ()
get_data(account);

double rate_fpaction, interest;


rate_fpaction = account.intepest_pate/100.0;
intepest = account.balance*pate_fpaction*(account.tepm/12.0);
account.balance = account.balance + intepest;

cout.setf(ios::fixed);
cout.setfCios:ishowpoint);
cout.ppecision(2);
cout "When youp CD matupes in "
account.tepm " months.\n"
"it will have a balance of $"
account.balance endl;
petupn 0;

// iostpeam.
void get_data(CDAccount& the_account)
{
cout "Entep account balance: $";
cin the_account.balance;
cout "Entep account intepest pate: ";
cin the_account.intepest_pate;
cout "Entep the numbep of months until matupity\n"
"(must be 12 O P fewep months): ";
cin the account.tepm;


Entep account balance: $100.00
Entep account intepest pate: 10.0
Entep the numbep of months until matupity
(must be 12 OP fewep months): 6
When youp CD matupes in 6 months,
it will have a balance of $105.00
,
int, char . . ,
CDAccount: my_account your__account.
CDAccount my_account. youp_account;

, ,
. ,
-.
. , CDAccount -
: double Int. - -
, .
. , CDAccount
( 6.1) : bal , 1 nterestrate tepm.
,
. - .
6.1. 257

- ,
. , account CDAccount,
:
account.balance
account.interest_rate
account.term

doubl , 1 nt.
, . -
:
account.balance = 1000.00;
account, interest^rate = 4.7;
account.term = iT;

. 6.1. -
,
. , , 6.1:
account.balance = account.balance + interest;

- account.balance
Interest - account.balance

struct CDAccount
{
double balance;
double interest_rate;
int term; // .

}:
1 int mainO
{ ^" ^ - ^ V balance ?
interest_rate ? ^ account
term ?

CDAccount account;
-~_^ balance 1000.00
interest_rate 7 > account
term ?

account.balance = 1000.00;
balance 1000.00
interest_rate 4.7 ? account
term ?

account, interest_rate = 4.7;


balance 1000.00
interest_rate 4.7 > account
^ term 11

account, term = l l T ^~~-.


---^,__6__._1^.
258 6.

, -
(.) , , 5.
, 5, ,
.
-
. ,
:
struct FertilizerStock
{
double quantity; // .
double nitrogen_content:
}:

struct CropYield
{
int quantity: // .
double size;
}:

, .
, :
FertilizerStock super_grow;
CropYield apples;

, ,
super_grow.quantity, -
apples.quantity. ,
(.), , quantity
.

.
,
, 1nt. ,
. , apples oranges
CropYield, :
apples = oranges;

:
apples.quantity = oranges.quantity;
apples.size = oranges.size;

:


.
6.1. 259

, , ,
, . ,
.
:

. ,
WeatherData , clata_po1 ntl data_poi nt2:
struct WeatherData
{
double temperature;
double w1nd_veloc1ty:
} data_po1ntl, data_po1nt2;
, ( struct)

, ,
.

(.)
(.) .

___. __

struct StudentRecord
{
int student_number;
char grade;
}:
int mainO
{
StudentRecord your_record:
your_record.student_number = 2001;
your_record.grade = 'A':
(.)
.


,
. , 6.1 getdata,
CDAccount .
.
,
CDAccount:
CDAccount shr1nk_wrap(double the^balance.
double the rate, i n t the term)
260 6.

CDAccount temp;
temp.balance = the_balance:
temp.interest_rate = the_rate;
temp.term = the_term;
return temp;
}
temp CDAccount.
,
. shrinkwrap
CDAccount:
CDAccount new_account;
new_account = shr1nk_wrap(10000.00. 5.1. 11);

:

,
. , Per
son Info, ,
, :
struct Date
{
1nt month; //
int day; //
int year; //
}:
struct Personlnfo
{
double height; //
int weight; //
Date birthday; //
}:
Personlnfo :
Personlnfo personl;
personl ,
:
cout personl.birthday.year;

. personl -
Personlnfo. - birthday
(.):
personl.birthday
, Personlnfo,
Date. - year
, personl. bi rth-
day.year.
6.1. 261


.
,
.
,
:
St ''uct Date
[
1
int month; //
int day; //
int year; //
}:
Date
duedate :
Date due_date ={12. 31. 2004};
,
, .
- due_date.month 12,
- duedate.day 31, - duedate.year ~
2004.
, ,
, .
,
, , ,
.


.

struct
{
_1 ___1;
_2 ___2;

_ ___:
}: // .

struct Automobile
{
int year;
int doors;
double horse_power;
char model;

^
262 6.


, . , :
struct Automobile
{
int year, doors:
double horse_power:
char model;
}:
.
,
:
Automobile my_car, your_car;

- (.): my_car .year, my_car .doors,


my_car. horse_power _. model.


1. ,
:
struct TermAccount
{
double balance;
double interest_rate;
i n t term;
char i n i t i a l l ;
char i n i t i a l 2 ;
}:
TermAccount account;
:
) account.balance;
) account.interest_rate;
) TermAccount.term;
) savings_account.initiall;
) account.initial2;
) account.
2. :
struct ShoeType
{
char style;
double price;
}:
:
ShoeType shoel. shoe2;
shoel.style = 'A';
shoel.price = 9.99;
6.1. 263

cout shoel.style " $" shoel.price endl;


shoe2 = shoel;
shoe2.price = shoe2.price/9:
cout shoe2.style " $" shoe2.price endl;
3. :
struct stuff
{
int b;
int ;
}
int mainO
{
Stuff x;
//
}
?
4. :
struct
{
int member_b;
int member_c;
}:
. mem-
ber_b member_c 1 2 .
.
-, . ,
.
5. .
struct Date
{
int month;
int day;
int year;
}:
) Date due_date = {12. 21};
) Date duejate = {12. 21. 2022};
) Date due_date = {12. 21. 20. 22};
r) Date due_date = {12. 21. 22};
? - , ,
.
6. ,
, ( )
( ).
char: '' 'S'. Employee-
Record.
264 6.

7. , .
( ShoeType 2.)
void read_shoe_record(ShoeType& new_shoe):
// new_shoe , .
8. , .
( ShoeType 2.)
ShoeType discount(ShoeType old_record);
// , .
// (price), 10 %.

9. StockRecord -
: shoejnfo ShoeType, 2, arrival_date
Date, 5.
10. StockRecord (. )
, (year) (arrivaldate),
2004.

6.2.
,
.

-
, . 5
, ^
-. , , C++,
,
, , -
.
. ,
-. ,
-.
6.2.
DayOfYear ,
, 1 4 .
, . .
1 nt: 1 , 2 . .
- int. DayOfYear
^ , ,
,
.
6.2. 265

- output,
. DayOfYear
.
DayOfYear ,
6.2, main. , public,
. ,
, , .
DayOfYear .
, struct class
month day output.
, .
- . (
C++ - -,
,
, .)
( ) ,
.
-
- , 5.
, 6.2 DayOfYear
:
DayOfYear today, birthday;
- output today :
today.outputO;
- output rthday :
birthday.outputO;
- ,
.
6.2 ,
, - output
. DayOfYear 6.2.
, .
6.2. -
// , .
// DayOfYear 6.3.
#1nclucle <1ostream>
using namespace std;

class DayOfYear
{
public:
void outputO; // -.
int month:
i n t day:
}: ^
266 6.

6.2 {)
i n t mainO
{
DayOfYear today, birthday;
cout "Enter today's date:\n";
cout "Enter month as a number: ";
Gin today.month;
cout "Enter the day of the month: ";
cin today.day;
cout "Enter your birthday:\n";
cout "Enter month as a number: ";
cin birthday.month;
cout "Enter the day of the month: ";
cin birthday.day;

cout "Today's date is: ";


today.outputO: // -.
cout "Your birthday is: ";
birthday.outputO; // -.

if (today.month == birthday.month
&& today.day == birthday.day)
cout "Happy Birthday!\n";
else
cout "Happy Unbirthday!\n";

return 0;

// iostream.
void DayOfYear::output0 // -.
{
cout "month = " month
". day = " day endl;


Enter today's date:
Enter month as a number: 10
Enter the day of the month: 15
Enter your birthday:
Enter month as a number: 2
Enter the day of the month: 21
TodayTs date is month = 10. day = 15
Your birthday is month = 2. day = 21
Happy Unbirthday!


, ,
, , ,
.
6.2. 267

- output DayOfYear :
void DayOfYear::output
:: ,
(.). ,
.
, ( ).
:: .
, (
), .
- DayOfYear::output 6.2.
, month day,
(.).
. output Day
OfYear, , ,
. , :
today. outputO;

, ,
.
:
{
cout "month = " today.month
". day = " today.day endl;
}
-
( , ) (.).

. DayOfYear
6.2: - 1 nput.
.
class DayOfYear
{
public:
void inputO;
void outputO;
i n t month;
i n t day;
}:
12. .
- set:
class Temperature
{
public:
void set(double new_degrees. char new_scale);
// - , .
268 6.

double degrees:
char scale; // 'F' -
// ' - .
};

13.
.

-
- ^ , ,
_ ::.

_ _::_(_)
{
_


// iostream:
I/O 7d DayOfYear:: output
{
cout " = " month
". = " day endl;
}
DayOfYear 6.2, month day
- . ,
.

(.) ::
(.), ::
, . ,
DayOfYear today:
DayOfYear today;

(.) today.
, output DayOfYear (. 6.2)
, today:
today. outputO;

::
- . , ,
- output DayOfYear:
void DayOfYear: loutputo

, :: , (.),
,
.
6.2. 269


double , C++:

. , doubl
. , C++ -,
, ,
, ^
,
, . ,
, .

, .
( 1 ,
), ,
, . ,
.
DayOfYear (. 6.2). DayOfYear
, ,
. ,
.
1 nt char,
(, ' J', ' ' ' '
January). ,
DayOfYear, .
, DayOfYear
output, . ,
, . ,
6.2 . ,
DayOfYear - month char,
,
, : - if...else.
,
,
. -,
, -
,
-. -
-, ,
. DayOfYear
6.3. , , -
month day - .
, , ,
, , , 1
.
270 6.

today .month, today .day,


bach_b1rthday.month bach_b1rthday.day.

6.3.
// , DayOfYear.
#1nclude <iostream> // DayOfYear,
// 6.2.
using namespace std;

class DayOfYear
{
public:
void inputO;
void outputO;

void set(int new_month, int new_day);


// : new_month new_day .
// : .

int get_month();
// : 1 . 2 . .

int get_day();
// .
private:
void check__date(); // -.
// -.
int month;
int day;

int mainO
{
DayOfYear today. bach_birthday;
cout "Enter today's date:\n";
today. inputO;
cout "Today's date is: ";
today. outputO;

bach_birthday.set(3. 21);
cout "J. S. Bach's birthday is: ":
bach_bi rthday.output();

if ( today.get_month() == bach_birthday.get_month() &&


today.get_day() == bach_birthday.get_day() )
cout "Happy Birthday Johann Sebastian!\n":
else
cout "Happy Unbirthday Johann Sebastian!\n":
return 0;
6.2. 271

// iostrean.
void DayOfYear::Input
{
cout "Enter the month as a number: ";
cin month;

// -.

cout "Enter the day of the month: ";


cin day;
check_date();

// input
// , , .
// , 7.

// iostream.
void DayOfYear::output
{
cout "month = " month
". day = " day endl;
}
void DayOfYear::set(int new_month. int new_day)
{
month = new_month;
day = new_day;
check dateO;

// - check_date
// , ,
// (. 14).

void DayOfYear::check_date()
{
if ((month < 1) II (month > 12) || (day < 1) || (day > 31))
{
cout "Illegal date. Aborting program.\n";
exit(l); // exit .

int DayOfYear::get_month
{
return month;
} ^
272 6.

6.3 {)
i n t DayOfYear::get_day()
{
return day;
}

Enter today's date:
Enter the month as a number: 3
Enter the day of the month: 21
Today's date is month = 3. day = 21
J. S. Bach's birthday is month = 3. day = 21
Happy Birthday Johann Sebastian!
6.3 ,
- .
private. ,
, ,
,
.
-
, ,
. private

- , -
.
- DayOfYear (. 6.3) .
-
- . ,
main:
DayOfYear today; // ,
today.month = 12; //
today.day = 2 5 ; //
, (
- DayOfYear).
month day ,
main :
cout today.month; //
cout today.day; //
if (today.month = = 1 ) //
cout "January";
- ,
, , -
.
, .
, 6.3
- ,
6.2. 273

- DayOfYear: :set, DayOfYear: :get__month Day


OfYear: :get_clay. ,
. , DayOfYear
:
class DayOfYear
{
public:
void inputO:
void outputO;
void setdnt new_month, int new_day):
// : new_month new_day .
// : .

int get_month():
// : 1 . 2 . .

int get_day():
// .

private:
void DayOfYear::check_date():
char firstjetter: // .
char secondjetter: // .
char th1rd_letter: // .
int day:
}:
- ,

. , get month :
1nt DayOfYear::get_month()
{
1f ( f i r s t j e t t e r == ' J ' && secondjetter == 'a'
&& thirdjetter == 'n')
return 1:
i f ( f i r s t j e t t e r == 'F' && secondjetter == 'e'
&& t h i r d j e t t e r == 'b')
return 2:

, , .
, , - DayOfYear: :set DayOfYear::
1 nput ,
. - DayOfYear: :check_date.
- month day , ,
, .

- , ,
. ( 14
- DayOfYear: :check_date ,
.)
274 6.

- .
, -
, ,
(, main ), . ,
- DayOfYear: :check_date (. 6.3) .
, - ,
- ,
.
public
, private . ,
DayOfYear -, DayOfYear::check_date,
( - ).
mai
, .
public private
.
pub! ic, (
private) ,
pri vate, (
public)
. ,
- do_something_else - morestuff
, .
class Sampled ass
{
public:
void do_something():
int s t u f f :
private:
void do_something_else():
char more_stuff:
public:
double do_yet_another_thing():
double even_more_stuff:
}:
, ,
(public private),
. ^
.

:
-
-
pri vate, , ,
- .
.
6.2. 275


, .
. .
class _
{
public:
//
__1
__2

__
private:
//
__-^1
__+2

}; // .
_J -,
-. ( public
private.)
.
class Bicycle
{
publi :
char get_color();
i nt number_of_speeds():
void setCint the_speeds. char the_color):
private:
int speeds:
char color:
}:
(
) , .
Bicycle:
Bicycle my_bike. your_bike:

:

== ,
. , ==
. 8 , ,
. ,
, .
, - .
, , -
- (
). - ,
276 6.

, . ,
6.3, - getmonth
getday. if...else
DayOfYear: today bach_birthday.
- , , getmonth getday,
, .
,
- ,
, .
-
; ,
. 8
, .
- , , set
6.3, - ,
. ,
.


,
.
- ,
- , .
- ~
. C++
, get ().
- ,
- , . C++
, set ().


14. - DayOfYear: :check_date 6.3
, 30 .
,
. 29 , .
( ,
, .)
15. , :
class Automobile
{
public:
void set_pri(double new_price):
void set_profit(double new_profit):
double get_price():
6.2. 277

private:
double price;
double p r o f i t ;
double g e t _ p r o f i t ( ) ;
}:
, main
:
Automobile Hyundai. jaguar;
- -
.
:
hyundai.price = 4999.99;
jaguar.set_pri ce(30000.97);
double a_price. a_profit;
a_price = jaguar.get_price();
a_profit = jaguar.get_profit();
a_profit = hyundai .get_profito;
if (hyundai == jaguar)
cout "Want to swap cars?";
hyundai = jaguar;
main?
16. , 15
pri vate. ?
17. public: private: .
, ,
(pub! ic) .
18. .
) publ i : ;
) private: ;
) ,
public: private:
;
) ,
public: private:
?

:

=
. , DayOfYear ,
6.3 ( - month day),
duedate tomorrow:
DayOfYear due_date, tomorrow;
278 6.

( , -
duedate tomorrow ):
due_date = tomorrow:
:
due_date.month = tomorrow.month;
due_date.day = tomorrow.day:
, , month day
DayOfYear^

: BankAccount
6.4 ,
.
,
, CDAccount ( ).
, BankAccount -
, . BankAccount
: ,
. BankAccount.
6.4. BankAccount
/ / , BankAccount.
#include <iostream>
using namespace std;

/ / .:
class BankAccount
{
public:
void setCint dollars, int cents, double rate); // - set .
// : Sdollars.cents;
// rate.

void set(int dollars, double rate);


// : Sdollars.OO;
// rate.

void updateO;
// :
// .

double get_balance();
// .

double get_rate();
// .
1
12 , =
() .
6.2. 279

void output(ostream& outs);


// : outs - .
// .
// :
// outs.
private:
double balance;
double interest_rate;

double fractionCdouble percent);


// . , fract1on(50.3)
// 0.503.
}:
Int malnO
{
BankAccount accountl. account2:
coiit "Start of Test:\n";
accountl.set(123, 99, 3.0); // - set.
cout "accountl initial statement:\n";
accountl.output(cout);

accountl.set(100, 5.0);
cout "accountl with new setup:\n";
accountl.output(cout):

accountl. updateO;
cout "accountl after update:\n";
account1.output(cout);

account2 = accountl;
cout "account2:\n";
account2.output(cout):
return 0;

// - set.

void BankAccount::set(int dollars, int cents, double rate)


{
if ((dollars < 0) II (cents < 0) || (rate < 0))
{
cout "Illegal values for money or interest rate.Xn";
exit(l);
}
balance * dollars + 0.01*cents;
interest rate = rate;
}
void BankAccount::set(int dollars, double rate)
{
i f ((dollars < 0) 11 (rate < 0)) ^
280 6.

6.4 {)
{
cout "Illegal values for money or interest rate.\n":
exitd):
}
balance = dollars;
interest rate = rate:
}
/ - -,
void BankAccount::update()

balance = balance + fraction(interest rate)*balance;

double BankAccount::fraction(double percent_value)

return (percent_value/100.0);

double BankAccount::get_balance()

return balance;

double BankAccount::get_rate()

return interest rate;

/ iostream.
/ cout. ,
void BankAccount::output(ostream& outs)
{
outs.setf(ios::fixed);
outs.setf(ios::showpoint);
outs.precision(2);
outs "Account balance $" balance endl;
outs "Interest rate " interest rate "%" endl;


Start of Test:
accountl initial statement:
Account balance $123.99
Interest rate 3.00^
accountl with new setup:
Account balance $100.00
Interest rate 5.00^
accountl after update:
Account balance $105.00
Interest rate 5.00^
account2:
Account balance $105.00
Interest rate 5.00^
6.2. 281

, , BankAccount
- fraction. ,
ma1 ,
BankAccount. -
. - fraction
:
- update. -
fraction ,
( ), 10.0 10 %,
( - 0.10).
. ,
$100,00 10 %,
$100,00 * 0.10, $10,00.
main - , up
date, , ,
:
account l.updateO:

- ( ) -
, .
, - BankAccount::update:
void BankAccount::update
{
balance = balance + fraction(interest_rate)*balance;
}
BankAccount::fraction (. 6.4).
- fraction - balance
interest_rate update. ,
accountl.updateO:

:
accountl.balance = accountl.balance + accountl.fract1on(accountl.interest_rate)*
accountl.balance;

, - fraction
, -.
, , BankAccount -
.
output. .
,
.
, .
- output ostream,
, cout, .
282 6.

6.4 ,
output :
accountl.output(cout);

, ,
,
5. :
account1.output(fout);

, accountl, tout.
BankAccount ,
.
- set.
,
. , .
double ,
-.
.
, ,
, . - set
, ,
, $1000, . ,
- :
.

:
, ,
, -.
,
.
.
( )
.
- .
-
.
- , .
- .
(.
19 20).
. ,
(. 21).
6.2. 283


,
( ), .
C++ -,
-. ,
C++ , .
C++ , .
, ,
.
, ,
, .

.


19. ,
( BankAccount 6.4):
double d1fference(BankAccount accountl. BankAccount account2):
// : accountl account2
// ( -);
// , accountl - account2.
20. ,
( BankAccount 6.4).
void double_update(BankAccount& the_account);
// : the_account
// ( -).
// : -
// .
. -.
21. ,
( BankAccount 6.4):
BankAccount new_account(BankAccount old_account):
// : old_account
// ( -);
// BankAccount
// , old_account.
, , ,
:
BankAccount accounts. account4;
accounts.set(999. 99. 5.5);
account4 = new_account(accounts);
account4.output(cout);
:
Account balance $0.00
Interest rate 5.50^
284 6.


-
. ,
,
, , .
C++ .
, -,
.
. ,
- .
, - ,
.
, . ,
BankAccount, .
. ,
,
void, .
,
BankAccount, 6.4.
(
):
class BankAccount
{
publ1 :
BankAccount(int dollars, int cents, double rate);
// Sdollars.cents
// (rate).

void set(int dollars, int cents, double rate);


void set(int dollars, double rate);
void updateO;

double get_balance();
double get_rate();
void output(ostream& outs);
private:
double balance;
double interest_rate;
double fractionCdouble percent);
}:

, BankAccount , . ,
- BankAccount
void, - . , ,
. ,
.
, ,
.
6.2. 285

BankAccount
:
BankAccount accountldO. 50. 2.0). account2(500. 0. 4.5);


accountl, accountl.balance 10.50,
accountl. 1 nterest_rate 2.0. , accountl
,
$10,50 2,0 %. , account2
$500,00 4,5 %.
. accountl,
BankAccount : 10, 50 2.0. account2
BankAccount 500, 4.5.
( C++):
BankAccount accountl. account2; // , ,
accountl.BankAccount(10. 50. 2.0): //
account2.BankAccount(500. 0. 4.5); //

,
. ,
.
-.
,
accountl account2:
BankAccount accountldO. 50. 2.0). account2(500. 0. 4.5);

-
. , BankAccount,
,
:
BankAccount::BankAccount(int dollars, int cents, double rate)
{
if ((dollars < 0) II (cents < 0) || (rate < 0))
{
cout "Illegal values for money or interest rate.Xn":
ex1t(l);
}
balance = dollars + 0.01*cents;
1nterest_rate = rate;
}
,
BankAccount : :: ( )
( -). , ,
void
.
- .
286 6.

, - (,
BankAccount: :set 6.4).
, . ,
, 6.5, BankAccount
: . -
Account , .
, :
BankAccount accountldOO. 2.3):

accountl $100,00
2,3 %.
, :
BankAccount account2:

account2
$0,00 0,0 %. ,
.
:
BankAccount account2(); //
.
BankAccount 6.5
- set.
- .
BankAccount (. 6.5) ,
- set (
6.4).


- , , ,
.
.

6.5.
// , BankAccount.
#1nclude <1ostream>
using namespace std;

// BankAccount
// , 6.4.
// :
class BankAccount
{
public:
BankAccount(int dollars, int cents, double rate);
// $dollars.cents
// rate.
6.2. 287

BankAccount(int dollars, double rate);


// $dollars.00
// rate.
// , .
BankAccountO;
// $0.00
// 0.0 ^. ^
void update ;
// :
// .

double get_balance();
// .
double get_rate();
// 1 .
void output(ostream& outs);
// : outs - ,
// .
// :
// outs,
private:
double balance;
double interest_rate;

double fractionCdouble percent):


// . fraction(50.3) 0.503.

int mainO
{
// account2 ,
// . .
BankAccount accountldOO. 2.3). account2;
cout "accountl initialized as follows:\n";
accountl.output(cout);
cout "account2 initialized as follows:\n";
account2.output(cout);
accountl = BankAccount(999, 99, 5.5); // BankAccount::BankAccount.
cout "accountl reset to the following:\n";
accountl.output(cout);
return 0;
}
BankAccount::BankAccount(int dollars, int cents, double rate)
{
if ((dollars < 0) II (cents < 0) || (rate < 0))
{
cout "Illegal values for money or interest rate.Vn";
exit(l);
} ^
288 6.

6.5 {)
balance = dollars + 0.01*cents;
interest_rate = rate;
}
BankAccount::BankAccount(int dollars, double rate)
{
if ((dollars < 0) II (rate < 0))
{
cout "Illegal values for money or interest rateAn";
exit(l):
}
balance = dollars;
interest_rate = rate;
}
BankAccount::BankAccount(): balance(O), interestrateCO.O)
{
// .
}
void BankAccount::output(ostrearn& outs)
{
outs.setf(ios::fixed):
outs.setf(ios:ishowpoint):
outs.precision(2);
outs "Account balance $" balance endl;
outs "Interest rate" interest rate "%" endl;


accountl i n i t i a l i z e d as follows:
Account balance $100.00
Interest rate 2.30^
account2 i n i t i a l i z e d as follows:
Account balance $0.00
Interest rate O.OOX
accountl reset to the following:
Account balance $999.99
Interest rate 5.50^

6.5 ,
, . :
BankAccount:'.BankAccount: balance(O), interest_rate(0.0)
{
// .
}
.
.
, ,
, ,
.
- , .
6.2. 289

, .
:
BankAccount: iBankAccountO
{
balance = 0;
interest_rate = 0 . 0 :
}

. ,
:
BankAccount::BankAccount(int dollars, double rate)
: balanceCdollars), interest_rate(rate)
{
1f ((dollars < 0) II (rate < 0))
{
cout "Illegal values for money or interest rateAn";
exit(l):
}
}
6.5.
,
.
,

-. .
.
, () .
, . ,
BankAccount,
$999,99 5,5 %:
accountl = BankAccount(999. 99. 5.5):
, ,
,

:
,
C++ ,
.
, ,
.
, set.
-
, ,
-
.
290 6.

. ,
.
, C++
. , C++
, ,
, .


,
. ,
,
.
:
__ _(^);
:
BankAccount accountldOO, 2.3);
:
= _{_);
:
account1 = BankAccount(200. 3.5):

, :
class Sampled ass
{
public:
//
Sampled ass(int parameterl. double parameter2):
void do_stuff():
private:
int datal:
double data2:
}:
Sampled ass :
SampleClass niy_object(7. 7.77):

SampleClass your_object:
.
,
, .
yourobject ,
, .
, ,
, :
6.2. 291

. ,
, ,
. Sam
pled ass :
class Sampled ass
{
public:
Sampled ass(int parameterl. double parameter2);
SampleClassO; // , .
void do_stuff():
private:
int datal;
double data2:
}:
Sampledass
your_object .
,
- , .
^:
SampleClass::Sampl eCl ass()
{
// .
}
, .

:
BankAccount ,
:
BankAccount accountldOO. 2.3):
,
:
BankAccount account2(): //
. ,
,
, , . ,
account2,
BankAccount.
,
. account2 :
BankAccount account2:
, ,
. BankAccount (. 6.5)
accountl = BankAccountO;
292 6.

,
, accountl.



. ,
, :
BankAccount accountl(100. 2.3);
, ,
:
BankAccount accountl;
:
BankAccount accountlO; //
.
accountl ,
BankAccount.


22. , (
-):
class YourClass
{
public:
YourClassdnt newjnfo. char more_new_1nfo);
YourClassO:
void do_stuff();
private:
int information;
char morejnformation;
}:
?
YourClass an_object(42. '');
YourClass another_object;
YourClass yet_another_object();
an_object = YourClass(99. 'B');
an_object = YourClassO;
an_object = YourClass;

23. DayOfYear 6.3,


() ?
i nt ( )
- ,
. ,
1 .
. .
6.3. 293

24. ,
-
.

6.3.
, .

,
1nt , , 1, -1, 2 . . ,
,
. , .
, int, : (+),
(-), (*), (/)
. ,
, .
, ,
, , . ,
, int double,
,
. ,
C++.
, , ,
.
, ,
. , ,
. ,
,
.


, int char,
, .
-. ,
BankAccount, 6.5, double.
( ):
class BankAccount
{
public:
BankAccountdnf dollars, int cents, double rate);
BankAccount(int dollars, double rate);
BankAccountO;
void updateO:
294 6.

double get_balance();
double get_rate():
void output(ostream& outs);
private:
double balance:
double interest_rate;
double fractionCdouble percent):
}:
, BankAccount, ,
BankAccount::update -
BankAccount. -
BankAccount::update:
void BankAccount::update
{
balance = balance + fraction(1nterest_rate)*balance:
}
- fraction
update .
void BankAccount::update
{
balance = balance + (interest_rate/100.0)*balance:
}
, , ,
update,
. ,
. double.
vacation_savings BankAccount,
doubl , -:
vacati on_savi ngs.balance
vacation_savings.interest_rate
vacati onsavi ngs
doubl , 1.3546+2 4.5, :
$135.46
4.5 %
BankAccount::output
.
, BankAccount
double, 1.3546+2 4.5, .
int, 135 46 (
), double - 0.045 (
4,5 %).
BankAccount , ,
:
class BankAccount
{
public:
6.3. 295

... . ...
private:
int dollars_part;
int cents_part:
double 1nterest_rate;
double fraction(double percent):
}:
, -,
. , get^balance
:
double BankAccount::get_balance()
{
return (dollars__part + 0.01*cents_part);
}
BankAccount: .'BankAccount(int dollars, int cents, double rate)
{
if ((dollars < 0) II (cents < 0) || (rate < 0))
{
cout "Illegal values for money or interest rate.Xn";
exit(l);
}
dollars_part = dollars;
cents_part = cents:
interest_rate = rate;
}
- ,
.
,
, ,
double. , int.
, BankAccount, ,
.
BankAccount

. ,
. ,
.
, .
- .

- ,
.
-.
8 9
,
.
296 6.


. C++,
- , ,
.

.
- . ,
, , main
, , .
, , (.
3 4). ,
,
, .
9 ,
, .
, ,
.
, , (
public- ) ( private-
- )
. ,

.
-
. ,
.
, ,
,
.
. , ,
,
, ,
,
. .

:
BankAccount
6.6 BankAccount,
.
: ,
.
, , 6.5 6.6,
- Interestrate, -.
6.3. 297

, , 4,7 %, 6.5
( , 6.4)
interest_rate 4.7. (. 6.6)
Interestrate 0.047,
. ,
,
- fraction.
, -
update, - 1 nterestrate
. ( 6.5)
: fraction update
.
6.6. BankAccount
/ / BankAccount.
#1nclude <1ostream>
#1nclucle <cmath>
using namespace std:

/ / , BankAccount
/ / . 6.5.

/ / :
class BankAccount
{
publ1 :
BankAccount(int dollars. Int cents, double rate):
// $dollars.cents
// rate.

BankAccount(int dollars, double rate):


// Sdollars.OO
// rate.

BankAccountO:
// $0.00
// 0.0 X.

void updateO:
// :
// .

double get_balance():
// .

double get_rate():
// ( ).

void output(ostream& outs):


// : outs - .
/ / . ^
298 6.

6.6 {)
II :
// outs,
private:
int donars_part:
int cents_part:
double interest^rate; // , 0.057 5,7 %.

double fraction(double percent);


// . , fraction(50.3)
// 0.503.

double percent(double fraction_value); // .


// . , percent(0.503)
// 50.3.
}:

int ma1n()
// main ,
// 6.5. .
{
BankAccount accountldOO. 2.3). account2:

cout "account1 initialized as follows:\n";


accountl.output(cout);
cout "account2 initialized as follows:\n";
account2.output(cout);

accountl = BankAccount(999. 99, 5.5);


cout "accountl reset to the following:\n";
accountl.output(cout);
return 0;
}
BankAccount::BankAccount(int dollars, int cents, double rate)
{
if ((dollars < 0) II (cents < 0) || (rate < 0))
{
cout "Illegal values for money or interest rate.Xn";
exit(l);
}
dollars_part = dollars:
cents_part = cents;
interest_rate = fraction(rate);
}
// -
// fraction update.
// .
BankAccount::BankAccount(int dollars, double rate)
{
if ((dollars < 0) II (rate < 0))
{
cout "Illegal values for money or interest rate.\n";
exit(l);
6.3. 299

donars_part = dollars:
cents_part = 0;
interest rate = fraction(rate):

BankAccount::BankAccount : dollars_part(0). cents_part(0). interest_,rate(0.0)

// .

double BankAccount::fraction(double percent_value)

return (percent_value/100.0):

/ cmath:
void BankAccount::update0

double balance = get_balance():


balance = balance + 1nterest_rate*balance:
dollars_part = floor(balance):
cents^part = floor((balance - dollars_part)*100):

double BankAccount::get_balance()

return (dollars^part + 0.01*cents_part):

double BankAccount::percent(double fraction_value)

return (fraction_value*100):

double BankAccount::get_rate()

return percent(1nterest_rate):

// iostream:
void BankAccount::output(ostream& outs)

outs.setfdos::fixed);
outs.setfdos: ishowpoint);
outs.prec1s1on(2);
// - get_balance get_rate
/ , ,
outs "Account balance $" get^balanceO endl;
outs "Interest rate " get rateO "%" endl;

BankAccount,
. -
, ,
300 6.

6.5. ,
( , 4,7 % 0.047), - get_rate
4.7, , .
- getbalance, ,
doubl , . ,
,
double, get_balance
, .
, -
.
,
, .
, - .
percent,
fraction. fraction
, percent
. , fract1on(4.7) 0.047,
percent(0.047) - 4.7.


, 3.
, :
,
,
, .
, , .

,
.


25. C++ ,
- -: ?
26. C++ ,
, ?
27. , C++,
, 6.3.
. , main
, .
, .
, ?
28. ,
6.6, -
.
301


.
.
- - ,
. ,
- - .
.
.
- , .
- ,
. , .
.
.
,

.
C++
, - ,
-.



1. :
) double;
) double;
) ,
;
) , savings^account ;
) char;
) TermAccount.
2. $9.99
$1.11

3. , ,
, g++ .
:
++ -fsyntax-only c6testgl.cc
probl.cc:8: semicolon missing after declaration of
'Stuff
302 6.

1.:8: extraneous '1nt' ignored


.:8: semicolon missing after declaration of
'struct S t u f f
( 'Stuff ^ .)
4. :
X = {1.2};

5. ) - .
: due_date.day = 21, due_date.month = 12,
due^date.year = 0. , ,
;
) : due_da-
te.month = 12, due_date.day = 21, due_date.year = 2002;
) : ;
) .
, . ,
, , , ,
.
6. struct Empl oyeeRecord
{
double wage_rate;
int vacation:
char status;
}:
7. void read_shoe_record(ShoeType& new_shoe)
{
cout "Enter shoe style (one letter): ";
cin new_shoe.style;
cout "Enter shoe price $";
cin new_shoe.price;
. }
8. ShoeType discount(ShoeType old_record)
{
ShoeType temp;
temp.style = old_record.style;
temp.price = 0.90*old_record.price;
return temp;
}

9. struct StockRecord
{
ShoeType shoe_info;
Date arrival date;

10. StockRecord aRecord;


aRecord.arrival_date.year = 2004;
11. void DayOfYear::input()
{
cout "Enter month as a number:
303

1 month;
cout "Enter the day of the month: ";
c1n day;
}
12. void Temperature::set(double new_degrees. char new_scale)
{
degrees = new_degrees;
scale = new_scale;
}
13. (.), ::
, .
DayOfYear , 6.2, today -
, - month
: today .month. - ::
, ,
::.
:
, ::
.
14. if,
7.
void DayOfYear::check_date()
{
if ((month < 1) II (month > 12)
II (day < 1) II (day > 31))
{
cout " Illegal date. Aborting program.\n";
exitd);
}
if (((month = = 4 ) || (month = = 6 ) || (month == 9)
II (month == I D )
&& (day 31))
{
cout "Illegal date. Aborting program.\n";
exitd);
}
if ((month == 2) && (day > 29))
{
cout "Illegal date. Aborting program.\n";
exitd);
}
}
15. hyundai.price = 4999.99; // (- price .)
jaguar.set_price(30000.97); //
double a_price. a_profit; //
a_price = jaguar.get_price(); //
a__profit = jaguar.get_profit(); // ( get_profit .)
a_profit = hyundai.get_profit(); // ( get_profit .)
if (hyundai == jaguar) // ( == .)
hyundai = jaguar; //
304 6.

16. ,
:
if (hyundai == jaguar) // ( == .)

17. private
. - -
. -
- ,

.
18. ) . ,
( ) ;
) , pri vate:;
) ,
private;
) ,
public.
19. :
double difference(BankAccount accountl. BankAccount account2)
{
return (accountl.get_balance() - account2.get_balance()):
}
, ,
balance :
double differenceCBankAccount accountl, BankAccount account2)
{
return (accountl.balance - account2.balance); //
}
20. void double_update(BankAccount& the_account)
{
the_account.update():
the_account.update();
}
, -, - update
.
21. BankAccount new_account(BankAccount old_account)
{
BankAccount temp;
temp.set(0. old_account.get_rate());
return temp;
}
22. YourClass an_object(42. 'A'); //
YourClass another_object; //
YourClass yet_another_object(); //
an_object = YourClass(99, 'B'); //
305

an_object = YourClassO: / /
an_object = YourClass; / /

// , ,
, , . ,
yet_another_object, :
yetanotherobject,
YourClass.
yetanotherobject,
, ,
:
YourClass another_object:

23. :
class DayOfYear
{
public:
DayOfYeardnt the_month. 1nt the_day);
// : the_month the_day
// ;
// .

DayOfYearO;

// 1 .

void inputO:

void outputO;

int get_month();
// : 1 . 2 . .
int get_day();
// ,
private:
void check_date();
int month;
int day;
}:
, - set,
.
-:
DayOfYear::DayOfYear(int the_month. int the_day)
{
month = the_month;
day = the_day;
check_date():
}
DayOfYear:: DayOfYearO
306 6.

month = 1;
day = 1;
}
DayOfYear: :set.
24. , .
:
DayOfYear::DayOfYear(1nt the_month. 1nt the_day)
: month(the_month). day(the_day)
{
check_date();
}
DayOfYear::DayOfYear0 : month(l). day(l)
{
// .
}
25. - . -
(
) . ,
,
-. .
26. - .
(, ,
-.) -
( )
. -
.
- - ( ).
27. ,
- ( )
. -
, -,
- ,
28. BankAccount::BankAccount(1nt dollars. 1nt cents,
double rate) : dollars_,part(dollars).
cents_part(cents). interest_rate(fraction(rate))
{
if ((dollars < 0) II (cents < 0) || (rate < 0))
{
cout
"Illegal values for money or interest rateAn";
exit(l):
}
}
BankAccount::BankAccount(int dollars, double rate)
: dollars_part(dollars). cents_part(0).
interest rate(fraction(rate))
307

i f ((dollars < 0) II (rate < 0))


{
cout
" I l l e g a l values for money or interest rateAn"
exitd);


1. ,
:
) ,
;
) ,
100;
) 50 % ,
25 % 25 %. (
.)
90 , 80 ( 90) , 70
( 80) , 60 ( 70) D, 60 F.
,
, ,
.
2. CDAccount ,
6.1, , -
, .
-: ,
,
, ,
.
, - input
1 stream - output
ostream. .
3. CDAccount 2, ,
.
BankAccount, 6.6.
1 nt:
. -,
, , ( ,
4,3 % 0.043 double).
,
, , 6.1.
308 6.

4. CounterType.
,
. , ,
,
, .
- ,
- . -
, . ,
-: ];
.
ostream .
.
5. Month
. - 1 nt,
(1 , 2 . .). ,
: , ;
, ;
, ,
(1 , 2 . .);
; - 1 nput,
, - 1 nput,
; - output, , -
output, ; -,
Month. -
1 nput output .
.
6. Month,
. -
char, .
.
7. ( .)
, 6.3,
5 6 Month -,
. - output ,
ostream .
, ,
, . ,
: cout
. -
. .
8. . -
add, sub, mul, d1v less, +, -, *,
/ <. , + b
. add (), < b .less ().
309

,
, 1/2, 2/3, 15/32, 65/4,
16/5.
int numerator () denominator ().
,
, .

int.
( , 1),
.
- input output.
i stream /
. ostream
/
.
- add, sub, mul div
. - less bool. ,
- neg,
, . main
.
:
/ + c/d = (a*d + b*c) / (b*d)
a/b - c/d = (a*d - b*c) / (b*d)
(a/b) * (c/d) = (a*c) / (b*d)
(a/b) / (c/d) = (a*d) / (c*b)
-(a/b) = (-a/b)
(a/b) < (c/d) (a*d) < (c*b)
(a/b) == (c/d) (a*d) == (c*b)
,
.
8,
, .
7

, .

.
, : if...else, while
clo...whi le.

: switch for. , if...else, while
clo...while ,
.

7 . 1 .

, .
, ,
, ,
, !
!


,
.
1 f ...el se,
(, while), .
,
true false, ++ , bool.
7.1. 311

, .
, +, -,
* /, ,
, == <, ,
, &&, 11 !. =, ! =, <, <= . .
true fal se.
, ,
,
.
,

. :
(X + 1) * (X + 3)

, 2.
, , 3 5, ,
, 15.
, ( + 1 ) ( + 3)
, . ,
3, ( + 1), 5, ( + 3).
.
, true fal se.
true false ,
. 7.1.

AND
! _2 _1 && _2
true true true
true false false
false true false
NOT
false false false
!()
true false
()R
false true
! _2 ! || _2
true true true
true false true
false true true
false false false

. 7 . 1 .


!(( < 3) II ( > 7))
312 7.

if...else while.
, 8,
( < 3) fal se, ( > 7) -
true,
:
!(false II true)

. 7.1, 11 ( OR -
) , true.
:
Ktrue)

! ( NOT - ),
, ! (true) false,
false.
, ,
, , &&, 11
!. .
: !,
(, >), && ||.
.
,
&& 11 ( ,
, ). ,
C++,
:
(temperature > 90) && (humidity > 0.90) && (pool_gate == OPEN)
> == &&,
,
. , ,
.
,
. ,
C++, . 7.2.
, , .
,
.
.
2.
,
(, + *),
(, && 11). ,
, :
(X + 1) > 2 II (X + 1) < - 3
7.1. 313

+ , - , + + , - - !
. , + / V
( ( )
*, /,% ^ f
+, -
<, >, <=, >=
==, ! =
&&

^ 11 ( )
. 7.2.

, . 7.2,
, :
((X + 1) > 2) II ((X + 1) < -3)

> < , 11.


; ,
. ,
:
+ 1 > 2 | | + 1<-3

,
, , ; >
<, 11.

, , C++
. . 7.1
11 &&, ,
.
:
(X >= 0) && ( > 1)

X , ( >= 0) false.
. 7.1, && false, false,
. , ,
false, .
11 . ,
, true, true
. C++
. ,
11 &&,
, .
.

. 11 &&
, .
314 7.

, .
, C++ ?
, .
, 11 &&, ,
.
, .
:
if ((family != 0) && ((k1ds/family) >= 2))
cout "Each child may have two pieces'";

family ,
. ,
(family != 0) false,
. C++ , 1 f
false, ((kids/family) >= 2),
. ,
.
C++ , .
, 1 true, f al se. ,
false , .
,
.
,
.

-~ true false
C++ bool, true,
, false .

:
int
, if...else
, true,
(, - ).
: if...else ,
true, time int
limit. :
if (!t1me > limit) // .

else

: , time
. limit.
7.1. 315

,
. ,
! >. ,
, , , :
(Itime) > limit
. time , , 36,
(Itime)? 36? C++
true, fal se,
136 false. >
, fal se i nt, 0.
, , ,
. , time 36, 1 imit
60, , i f...el se true,
, time > limit.
: (Itime) ,
> limit
> 60, fal se. ,
false, true.
.
I. ,
, , :
i f (Ktime > limit))

else

!. ,
, :
i f (time <= limit)

else

,
,
. ,
, , .


1.
, count , limit 10.
: true false.
) (count == 0) && (limit < 20);
) count == && limit < 20;
316 7.

) (limit > 20) || (count < 5);


) !(count == 12);
) (count == 1) && (X < );
) (count < 10) II (X < );
) '(((count < 10) II (X <)) && (count >= 0));
) ((limit/count) > 7) || (limit < 20);
) (limit < 20) II ((limit/count) > 7);
) ((limit/count) > 7) && (limit < 0);
) (limit < 0) && ((limit/count) > 7);
) (5 && 7) + (!6).
2. C++,
. .
3. :
2< X < 3
C++ . , ,
C++, ,
2 3.
4. :
J = -1:
if ((j > 0) && (l/(j+l) > 10))
cout i endl:

,
bool.
if...else,
, .

.
, ,
( )
,
, , .
,
i f (((rate >= 10) && (rate < 20)) || (rate == 0))
{

}
7.1. 317

, :
i f (approprlate(rate))
{


bool appropriatednt rate)
{
return (((rate >= 10) && (rate < 20)) 11 (rate == 0));


5. in-order,
int. true,
; false. ,
in^orderd. 1. 3) 1n_order(l. 2. 2) true,
in_order(l. 3.2) false.
6. even, 1 nt
bool. true,
, false .
7. 1s_d1g1t,
char bool. true,
, false .
8. is_root_of,
1nt bool. true,
, false
.

( )
,
1 nt. .
1 nt
. ,
:
enum MonthLength {JAN_LENGTH = 31. FEB_LENGTH = 2 8 .
MAR_LENGTH = 31. APR_LENGTH = 30. MAY_LENGTH = 31.
JUN_LENGTH = 30. JULJENGTH = 31. AUG_LENGTH = 31.
SEP_LENGTH = 30. 0CT_LENGTH = 31. N0V_LENGTH = 30.
DEC_LENGTH = 31}:

, ,
, .
318 7.

,
, 0. ,

enum Direction { NORTH = 0. SOUTH = 1. EAST = 2. WEST = 3};
:
enum Direction { NORTH. SOUTH. EAST. WEST };

,
, .
, :
enum MyEnum { ONE = 17, TWO. THREE. FOUR = -3. FIVE }:
ONE 17, TWO
, 18, THREE - 19, FOUR - -3 FIVE -
, -2.
,
.

7.2.
, , ?
, , .

,
, .
if...else,
.
.

if...else
, if...else if ,
.

.
, if...else, while do...while. . 7.3
, , -
cout if...else, , , if.
,
. . 7.3
.
, cout
, .
7.2. 319

, ,
.

1f (count > 0)
1f (score > 5)
cout "count > 0 and score > 5\n";
else
cout "count > 0 and score <= 5\n":|

. 7.3. if...else, if

:

, if...else
.
, ,
- ( ), .
, .
.
, 3/4. :
, 1/4.
. .
( , 3/4):
.
, :
i f (fuel_gauge_read1ng < 0.75)
i f (fuel_gauge_reacling < 0.25)
cout "Fuel yery low. Caution!\n";
else
cout "Fuel over 3/4. Don't stop now!\n";
Ha ,
C++ :
.
. ,
i f el se. ,
i f .
, , else, ,
.
, :
i f (fuel_gauge_reading < 0.75)
i f (fuel_gauge_reading < 0.25)
cout "Fuel yery low. Caution!\n";
else
cout "Fuel over 3/4. Don't stop now!\n";
320 7.

,
el se 1 f.
else, 7.1 ,
.
else
1f, else.
.
, , ,
, .
if...else? :
,
, . ,
, ,
.
1 f...el se ,
if...else 7.1.
,
cout, . ,
7.1 ( if...else)
cout "Fuel over 3/4. Don't stop now!\n";
.
.
,
, if...else.
7.1.
// 1f...else.
#include <iostream>
using namespace std;
int mainO
{
double fuel_gauge_reading;
cout "Enter fuel gauge reading: ";
cin fuel_gauge_read1ng;

cout "First with braces:\n";


i f (fuel_gauge_reading < 0.75)
{
If (fuel_gauge_reading < 0.25)
cout "Fuel very low. CautionlXn";
}
else
{
cout "Fuel over 3/4. Don't stop now!\n"
}
cout "Now without braces:\n";
i f (fuel_gauge_reading < 0.75)
i f (fuel_gauge_reading < 0.25)
7.2. 321

cout "Fuel very low. Caut1on!\n";


else
cout "Fuel over 3/4. Don't stop now!\n";

return 0:
}
1
Enter fuel gauge reading: 0.1
First with braces:
Fuel very low. Caution!
Now without braces:
Fuel very low. Caution!

2
Enter fuel gauge reading: 0.5
First with braces:
Now without braces:
Fuel over 3/4. Don't stop now!

if...else
if...else ,
.
,
if...else. , ,
.
number, guess.
,
:
"Too high.", guess > number.
"Too low.", guess < number.
"Correct!", guess == number.


,
if...else. , :
if (guess > number)
cout "Too high.":
else if (guess < number)
cout "Too low.";
else if (guess == number)
cout "Correct!";

.
, :
if (guess > number)
cout "Too high.";
else
if (guess < number)
cout "Too low.";
else
322 7.

if (guess == number)
cout "Correct!";
Ho ,
.
el se, - ,
.
;,
, ,
:
if (guess > number)
cout "Too high.";
else if (guess < number)
cout "Too low.";
else // (guess == number)
cout "Correct!";
i f ...el se
, .
, -
, .
, .
else if,
, .

if...else

i f (__1)
_1
else i f {__2)
_2

else i f {__)
_
else
_ ___

if ((temperature < -10) && (day == SUNDAY))
cout "Stay home.":
else if (temperature < -10) // day != SUNDAY
cout "Stay home, but call work.":
else if (temperature <= 0) // temperature >= -10
cout "Dress warm.":
else // temperature > 0
cout "Work hard and play hard.":
,
, .
, ____.
7.2. 323

:
7.2 ,
1 f ...el se.
, ,
( ), ,
.
.
1. $15 000 .
2. $15 001 $25 000 5 % .
3. $25 000 10 % .
, 7.2, if...else
. .
, ,
. ,
net^income 15000. ,
else i f ((netjncome > 15000) && (netjncome <= 25000))

else i f (netjncome <= 25000)
7.2. if...else
// .
#include <iostream>
using namespace std;

double taxCint netjncome):


// : netjncome
// , .
// ,
// :
// $15 000 : 5 %
// $15 001 $25 000 10 ^ - $25 000.

int mainO
{
int net_income:
double tax_bill:
cout "Enter net income (rounded to whole dollars) $":
cin netjncome:

tax_bill = tax (netjncome):

cout.setf(iOS::fixed):
cout.setf(i OS::showpoi nt):
cout.precision(2):
cout "Net income = $" netjncome endl
"Tax b i l l = $" tax b i l l endl: ^
324 7.

7.2 ()
return 0:

double t a x d n t net income)


{
double five_percent_tax. ten_percent_tax;

if (netjncome <= 15000)


return 0;
else if ((netjncome > 15000) && (netjncome <= 25000))
// 5 X $15 000
return (0.05*(netjncome - 15000)):
else / / netjncome > $25,000
{
// five_percentjax '^ S X $15 000 $25 000.
five_percent tax = 0.05*10000;
// ten_percent_tax = 10^ $25.000.
ten_percent_tax * 0.10*(netjncome - 25000);
return (five_percent_tax + ten_percent_tax);
}


Enter net income (rounded to whole dollars) $25100
Net Income = $25100
Tax bill = $510.00


9.
Int X = 2;
cout "Start\n";
i f (X <= 3)
i f (X != 0)
cout "Hello from the second ifAn";
else
cout "Hello from the else.Vn";
cout "End\n":

cout "Start again\n";


if (X > 3)
if (X != 0)
cout "Hello from the second if.\n":
else
cout "Hello from the else.\n";
cout "End againXn";

?
10.
i n t extra = 2;
i f (extra < 0)
cout "small";
else if (extra == 0)
7.2. 325

cout "medium";
else
cout "large";

?
. , 10,
:
i n t extra = -37;

12. , 10,
:
i n t extra = 0;

13.
i n t X = 200;
cout "StartXn";
i f (X < 100)
cout "First Output.\n";
else if (X > 10)
cout "Second Output.\n";
else
cout "Third Output.\n";
cout "End\n";
?
14. , 13,
( > 10) ( > 100)?
15.
int X = SOME_CONSTANT;
cout "Start\n";
if (X < 100)
cout "First Output.\n";
else if (X > 100)
cout "Second Output.\n";
else
cout X endl;
cout "End\n";
? SOMECONSTANT
Int, 100.
16. if...else, int
:
W < , < < 100, > 100
.
17. cout,
:
enum Direction {N, S. E, W};
//...
cout W " " E " " S " " N endl;
326 7.

18. cout
:
enum Direction {N = 5. S = 7. = 1. W};
//...
cout W " " E " " S " " N endl;

switch
,
i f ...el se. C++ ,
. switch,
. 7.3.

.
. '', ''
' ' . ' D' ' F'
. grade,
, , '', '', ', 'D' 'F',
cout, default.
switch
7.3 switch.
7.3. switch
// , switch.
#1nclude <1ostream>
using namespace std;

int mainO
{
char grade:
cout "Enter your midterm grade and press return: ":
cin grade;

switch (grade)
{
case 'A':
cout "Excellent, "
"You need not take the final.Xn";
break;
case 'B':
cout "Very good. ";
grade = 'A';
cout "Your midterm grade is now."
grade endl;
break;
case ' C :
cout "Passing.\n";
break;
case 'D':
case 'F':
cout "Not good. "
7.2. 327

"Go study.\n":
break;
default:
cout "That is not a possible grade.\n";
}
cout "End of program.\n";
return 0:
}

1
Enter your midterm grade and press return: A
Excellent. You need not take the final.
End of program.
2
Enter your midterm grade and press return:
Very good. Your midterm grade is now A
End of program.
3
Enter your midterm grade and press return: D
Not good. Go study.
End of program.
4
Enter your midterm grade and press return: E
That is not a possible grade.
End of program.
switch ,
. ,
switch. 7.3
char. switch
bool, enum,
, . switch
,
, case. ,
,
case. ,
' ', C++
:
case ' ' :

, . ,
switch case .
break break,
. ,
case, ,
break. switch .
328 7.

break, case
.
,
case. switch (. 7.3)
'D' 'F'. switch
. ,
7.3 '', '',
case ' ' :
cout "Excellent. "
"You need not take the final.\n":
break:

:
case ' ' :
case ' * :
cout "Excellent. "
"You need not take the final.Vn";
break;

To .
case ,
, ,
default. default switch ,
, switch .
default, ,
case ,
.
7.3.

switch

s w i t c h ( )
1
case _1:
^_ _1
break;
case _2\
___2
break;

case _\
___
break;
default:
___
}
7.2. 329


int vehicle_class;
cout "Enter vehicle class: ";
cin vehicle_class;
switch (vehicle class)
! {
case 1:
cout "Passenger car.";
toll = 0.50;
break; // break.
// $1.50.
case 2:
cout "Bus.";
toll = 1.50;
break;
case 3:
cout "Truck.";
toll = 2.00;
break;
default:
cout "Unknown vehicle class!";
}

: break
switch
switch break,
. , switch
, . switch,
switch.
break, , vehicle_class
1, , , ,
case 1;

, switch,
case.
, , ,
, . , toll
1.50, 0.50, . ,
case, ,
break switch.

switch

if...else , switch,
switch,
if...else. switch
330 7.

, ,
.
, .
:
. 7.4 ,
. ,
. (
,
. 4.)
7.4. switch
/ / , .
#include <iostream>
using namespace std;

void show_assignment();
// .
void show__grade();
// .
void give_hints();
// .
i n t mainO
{
i n t choice;

do
{
cout endl
"Choose 1 to see the next homework assignment.\n"
"Choose 2 for your grade on the last assignment.\n"
"Choose 3 for assignment hints.Nn"
"Choose 4 to exit this program.\n"
"Enter your choice and press return: ":
cin choice;
switch (choice)
{
case 1;
showassignmentO;
break;
case 2:
showgradeO:
break;
case 3:
g1ve_hints();
break;

case 4:
cout "End of Program.\n";
break;
default:
7.2. 331

cout "Not valid choice.\n"


"Choose again.\n";
}
}wh11e (choice != 4);
return 0;
}
. . . showjissignment, show_grade g1ve_h1nts. . . .


Choose 1 to see the next homework assignment.
Choose 2 for your grade on the last assignment.
Choose 3 for assignment hints.
Choose 4 to exit this program.
Enter your choice and press return: 3

Assignment hints:
Analyze the problem.
Write an algorithm in pseudocode.
Translate the pseudocode into a C++ program.

Choose 1 to see the next homework assignment.


Choose 2 for your grade on the last assignment.
Choose 3 for assignment hints.
Choose 4 to exit this program.
Enter your choice and press return: 4
End of Program.

:

switch if...else
,
. switch,
7.4, 1, 2 3
,
.
switch, ,
.

switch if...else .
, ,
,
.
,
, .

332 7.

. ,
7.5. ,
.

. , ,
. if...else.
subtotal,
,
1f...else.
, 7.5, subtotal
. , ,
, , .
subtotal -

.
: ,
, .
,
,
. ( ,
, , .)


C++, .
,
, ,
.

7.5.
/ / , .
#inclucle <iostreani>
using namespace std;
const double TAX_RATE = 0 . 0 5 ; %

int mainO
{
char sale_type;
int number;
double price, total;
cout "Enter price $";
cin price;
cout "Enter number purchased: ";
cin number;
cout "Type W if this is a wholesale purchase.\n"
"Type R if this is a retail purchase.\n";
7.2. 333

"Then press return.\n":


cin sale_type;

i f ((sale_type == 'W') || (sale_type == 'w'))


{
total = price * number:
}
else i f ((sale_type == 'R') || (sale_type == ' r ' ) )
{
double subtotal: // .
subtotal = price * number;
total = subtotal + subtotal * TAX_RATE:
}
else
{
cout "Error in input.\n";

cout.setf(ios:-.fixed);
cout.setf(ios::showpoint);
cout.precision(2);
cout number " items at $" price endl;
cout "Total Bill = $" total;
if ((sale_type == 'R') || (sale_type == 'r'))
cout " including sales tax.\n";

return 0;
}


Enter price $10.00
Enter number purchased: 2
Type W if this is a wholesale purchase.
Type R if this is a retail purchase.
Then press return.
R
2 items at $10.00
Total Bill = $21.00 including sales tax.

, .
, , ,
, .
,
.
, ,
. ,
,
, .
,
. ;
.
334 7.


,
, .
.
.
, .

: ,

, { },
. , ,
. .


19.
1nt f1rst_cho1ce = 1;
switch (first_cho1ce + 1)
{
case 1:
cout "Roast beef\n";
break;
case 2:
cout "Roast worms\n";
break;
case 3:
cout "Chocolate ice creamXn";
case 4:
cout "Onion ice cream\n";
break;
default:
cout "Bon appetit!\n";
}
?
20. ,
:
i n t first_choice = 3;
21. , :
int first_choice = 2;
22. , 19,
:
i n t first_choice = 4;

23.
i n t number = 22;
{
7.3. C++ 335

int number = 42;


cout number " ";
}
cout number:
?
24. ,
, ,
.

{
int X = 1:
cout X endl;
{
cout X end1;
int X = 2;
cout X endl;
{
cout X endl;
int X = 3;
cout X endl;
}
cout X endl;
}
cout X endl:
}
?

7.3. C++
, ,
.
-
,
.
while do...wh1le.
,
.

.

while
while
do...wh11 .
, ,
. whi 1
, false,
336 7.

. clo...while ,
,
. wh11 do...wh11
.
, true, .
f! se, .
, , while
, false,
. :
, ,
do...whi 1 . , whi 1
, . ,
, ,
.
.
whi 1 , :
whi1 {_)
II .

while , ,
:
while (_))
{
II
_1
_2

_
}
dc.while ,
:
do
II ,
whi 1 (_)1() :

, :
do
{
// .
_1
_2

_
}whi1 {_):
7.3. C++ 337




. , :
int number = 41;
number++;
cout number;

42,
,
, + -
. , number++ ,
:
2*(number++)

number++ number,
. :
int number = 2;
int value_proclucecl = 2*(number++);
cout value_produced endl;
cout number endl;

OH :
4
3

2*'(number++). C++
number, .
, number++ 2,
number ( 3).
++ ,
. , , ++ .
v++ v .
, ++
, . ++v
v , .
:
int number = 2;
int value_produced = 2*(++number);
cout value_produced endl;
cout number endl;
OH , ++
number. -
:

3
338 7.

, , ++nuniber number++,
: .
. ++ ,
, ;
, .
, 7.6,
while .
.
7.6.
// .
#1ncludG <iostream>
using namespace std:

int ma1n()
{
int number_of_1terns, count.
calones_for_1tem. total_calories;
cout "How many Items did you eat today? ";
cin number_of_iterns:

total_calories = 0;
count = 1:
cout "Enter the number of calories in each of the\n"
number_of_items " items eaten:\n";

while (count++ <= number_of__iterns)


{
cin calories_for_item;
total_calories = total_calories
+ calories_forJtem:
}
cout "Total calories eaten today = "
total_calories endl:
return 0:


How many items did you eat today? 7
Enter the number of calories in each of the
7 items eaten:
300 60 1200 600 150 1 120
Total calories eaten today = 2431

Bee
, ,
, .
:
int number = 8:
int value_produced = number--:
7.3. C++ 339

cout value_procluced endl:


cout number endl:

OH :
8
7

:
1nt number = 8;
1nt value_produced = --number;
cout value_produced endl;
cout number endl;

:
7
7

number-- number
, --number
.
,
. , ( + )++, -- ( + ), 5++
, C++ .

25.
int count = 3;
while (count-- > 0)
cout count " ";
?
26.
int count = 3;
while (--count > 0)
cout count " ";
?
27.
int = 1;
do
cout n " ";
while (n++ <= 3); ,
?
28.
int = 1;
do
cout n " ";
while (++n <= 3);
?
340 7.

for
while do...while
, , while.
, C++
.
1,
2, 3 . . .
, 1 10,
:
sum = sum + n;

1,
.
:
sum = 0;
= 1;
while ( <= 10)
{
sum = sum + ;
++:
}
whi 1, C++
for ( for). ,
:
sum = 0;
for ( = 1 ; <= 10; ++)
sum = sum + ;

for, : , while.
. , ,
whi 1 for .
, sum 0.
.
:
= 1; <= 10; ++ sum = sum + ;

for , whi 1 ,
, .
,
for, ,
. for.
for for,
, ,
. for :
f (_; _; _)

, ,
, .
7.3. C++ 341

.
for :
for ( = 1; <= 10; ++)

= 1 ,
1. <= 10 , ,
10. , ++,
,
.
for (
!) ,
. ( ,
, ,
.)
. 7.4 for
while. ,
for, ; whi 1 , ;
. , ,
.
7.7 for ( )
. , ,
.
, for.

. ,
,
, .
7.7. for

/ / for.
#include <1ostream>
using namespace std; /

int mainO
{
int sum = 0:
for (int n = 1; n <= 10; --) // , n
// ,
sum = sum + ;

cout "The sum of the numbers 1 to 10 is "


sum endl;
return 0:


The sum of the numbers 1 to 10 is 55
342 7.

for

f o r {_: -, _)
_

for (number = 100; number >= 0: number--)
cout number
" bottles of beer on the shelfAn":

while

^:
while {_)
{
_
_:
}

number 100;
while (number > 0)
{
cout number
" bottles of beer on the shelfAn";
number--;
}

100 bottles of beer on the shelf.
99 bottles of beer on the shelf.

0 bottles of beer on the shelf.

. 7.4. for

ANSI C++ ,
for . C++
, ,
.
,
, .
, ANSI
for ,
. , ,
, ,
, .
7.3. C++ 343

for .
for C++
( !) .
.
for, 7.7,
:
sum = sum + ;

^ ,
. for .
:
for {_: _: ^)
{
_1
J

jn
]
:
for ( i n t number = 100; number >= 0; number--)
{
cout number
" bottles of beer on the shelf.\n";
if (number > 0)
cout "Take one down and pass it around.\n";
}
for
.
.
, double. ,
for:
for (n = 1; n <= 10; n = n + 2)
cout "n is now equal to " n endl;

for (n = 0; n > -100; n = n - 7)


cout "n is now equal to " n endl;

for (double size = 0.75; size <= 5; size = size + 0.05)


cout "size is now equal to " size endl;

,
,
.
. for:
for (double X = pow(y. 3.0); x > 2.0; x = sqrt(x))
cout "x is now equal to " x endl;
344 7.

: for
for.
, .
for (int count = 1: count <= 10; count++); // ,
cout "HelloVn":

, ,
11. , ,
, . !
,
. Hel 1
. ? ,
, .
C++ ,
. ,
++,
++;

.
, ,
. ,
. :
for ( i n t count = 1; count <= 10; count++);

for,
.
,
, .
, , !

. - for
, .
cout, Hello
:
cout "Hello\n":

, for ,
, .


C++
.
C++.
7.3. C++ 345

,
.
,
, for. ,
, .
while do...while.
:
, do...wh11 , ,
, while.
, while, ,
; . ,
,
, .
while.


29.
for (int count = 1: count < 5; count++)
cout (2 * count) " ";
?
30.
for ( i n t n = 10; n > 0; n = n - 2)
{
cout "Hello";
cout n endl;
}
?
31.
for (double sample = 2. sample > 0; sample = sample - 0.5)
cout sample " ";
?
32. :
) , 1/2 + 1/3 + 1/4 + 1/5 + ... +
+1/10;
) ;
) ,
;
)
.
33. for.
) i n t i = 1;
while ( i <= 10)
346 7.

{
i f ( i < 5 && 1 != 2)
cout 'X';
i++;
}
) int 1 = 1 ;
while ( i <=10)
{
cout 'X';
i = i + 3:
}
) long m = 100;
do
{
cout 'X';
m = m + 100;
} while (m < 1000);

34. :
int n - 1024;
int log = 0;
for (int i = 1; i < n; i = i * 2)
1og++;
cout n " " log endl;
1 .
35. :
i n t = 1024;
i n t log = 0;
for ( i n t i = 1; i < n; i = i * 2);
log-H-;
cout n " " 1 og endl;

.
36. :
i n t = 1024;
i n t log = 0;
for ( i n t i = 0; i < n; i = i * 2)
log-H-;
cout n " " log endl;

:

2, whi 1 do...whi 1 ,
, . -,
,
( ) .
, . -,
7.3. C++ 347

, .
for.

break
break switch.
.
. ,
, ,
. 7.8
, ,
sum.
, ,
, break.

break
break .
,
, . break
: while, do...while for. ,
switch.

7.8. break
/ / 10 .
#include <iostream>
using namespace std;

int mainO
{
int number, sum = 0. count = 0;
cout "Enter 10 negative numbers:\n";

while (++count <= 10)


{
cin number:

if (number >= 0)
{
cout "ERROR: positive number"
" or zero was entered as the\n"
count "th number! Input ends "
"with the " count "th number.\n"
count "th number was not added in.\n":
break;
}

sum = sum + number:


} ^
348 7.

7.8 {)
cout sum " 1s the sum of the first "
(count - 1) " numbers.\n";

return 0;


Enter 10 negative numbers:
-1 -2 -3 -4 -5 -6 -7 -8 -9 -10
ERROR: positive number or zero was entered as the
4th number! Input ends with the 4th number.
4th number was not added 1n.
-6 1s the sum of the first 3 numbers.

: break
break .

break, ,
.


37.
1nt = 5;
while (-- > 0)
{
If ( == 2)
break;
cout n " ";
}
cout "End of Loop.":
?
38.
Int = 5;
while (-- > 0)
{
If ( == 2)
ex1t(0);
cout n " ";
}
cout "End of Loop.":
?
39. break? ?
7.4. 349

7.4.
, , .

:
;
;
.
, -
; , ,
.


.
,
:
sum = 0;
this_many :
1 next;
sum = sum + next;
.
thi smany .
sum.
for:
i n t sum = 0;
for (1nt count = 1; count <= this_many; count++)
{
c1n next;
sum = sum + next;
}
,
sum :
sum = sum + next;

. ,
, ,
.
sum . ,
sum + next next. sum
0.
. :
int product = 1 ;
for (1nt count = 1; count <= th1s_many; count++)
350 7.

{
cin next;
product - product * next;
}
product ,
. product ,
- (
). 1.
product
( next), ,
next .


for ,
.

7-/7_
_
for
f o r ( i n t = 1 ; <= j)d3\ ++)
_

for (int count = 1; count <= 3; count--)
cout "Hip. Hip. HurrayXn";


,
. .
1. .
2. .
3. .
4. .
,
- ,
.
.
,
, . :
sum = 0:
cout "Are there any numbers in the list? (Type\n"
"Y and Return for Yes. N and Return for No): ";
char ans:
7.4. 351

c1n ans:
while (Cans == 'Y') || (ans == ' y ' ) )
{
cout "Enter number: ";
cin number;
sum = sum + number;
cout "Are there any more numbers? (TypeXn"
"Y for Yes. N for No. End with Return.): ";
cin ans;
}

. .
, , ];
, . ,
. ,
,
, . :
cout "Enter list of nonnegative integers.\n"
"Place a negative integer after the list.Xn";
sum = 0;
cin number;
while (number >= 0)
{
sum = sum + number;
cin number;
}
, ,
. 1, 2 3
:
12 3-1

, -1, ,
sum.
,

, , .
,
, ,
.
, ,
, , ,
. 5.

:
, ;
;
.
352 7.

, , ,
.
, ,
. ,
.
, , .
, .
,
. ,

. ,
. ,
, .
number. ,
, ,
.

.
, ,
.
,
. ,
. , 1.
, ,
. 90 .
, compute_grade,
, .
1nt = 1;
grade = compute_grade(n);
while (grade < 90)
{
n++;
grade = compute_grade(n);
}
cout "Student number " n " may be a tutor.\n"
"This student has a score of " grade endl;
grade.
, .
, 90 ?
computegrade.
, . ,
, , 100 , ,
.
,
,
7.4. 353

, ,
. ,
( numberofstudents
):
int = 1:
grade = compute_grade(n);
while ((grade < 90) && (n < number__of_students))
{
--;
grade = compute_grade(n);
}
if (grade >= 90)
cout "Student number " n " may be a tutor.\n"
"This student has a score of " grade endl:
else
cout "No student has a high score.";


, 7,9,
.
.
,
.
7.9. 1
/ /
/ / .
#inc1ude <1ostream>
using namespace std:

void instructionsO:

void get_one_total(int& t o t a l ) :
/ / : ,
/ / .
/ / : total - .

int mainO
{
instructionsO:
int number_of_reports:
cout "How many conservationist reports are there? ":
cin number_of_reports:
int grand_total = 0. subtotal, count:
for (count = 1: count <= number_of_reports: count++)
{
cout endl "Enter the report of "
"conservationist number " count endl:
get^one total (subtotal); ^
354 7.

7.9 ()
cout "Total egg count for conservationist
" number " count " is "
subtotal endl;
grand_total = grand_total + subtotal;

cout endl "Total egg count for a l l reports


grand_total endl;

return 0:

// iostream.
void instructions
{
cout "This program tallies conservationist reports\n"
"on the green-necked vulture An"
"Each conservationist's report consists of\n"
"a list of numbers. Each number is the count of\n"
"the eggs observed in one"
" green-necked vulture nest.\n"
"This program then tallies"
" the total number of eggs.\n";
}
// iostream.
void get_one_total(int& total)
{
cout "Enter the number of eggs in each nest.Xn"
"Place a negative integer"
" at the end of your list.\n";
total = 0;
int next:
cin next:
while (next >= 0)
{
total = total + next:
cin next:
}
}


This program tallies conservationist reports
on the green-necked vulture.
Each conservationist's report consists of
a list of numbers. Each number is the count of
the eggs observed in one green-necked vulture nest.
This program then tallies the total number of eggs.
How many conservationist reports are there? 3

Enter the report of conservationist number 1


Enter the number of eggs in each nest.
Place a negative integer at the end of your list.
7.4. 355

1 0 0 2-1
Total egg count for conservationist number 1 is 3

Enter the report of conservationist number 2


Enter the number of eggs in each nest.
Place a negative integer at the end of your list.
0 3 1-1.
Total egg count for conservationist number 2 is 4

Enter the report of conservationist number 3


Enter the number of eggs in each nest.
Place a negative integer at the end of your list.
-1
Total egg count for conservationist number 3 is 0

Total egg count for all reports = 7

,
. get_one_total void
.
,
, . get_one_total
for .
, .
7.9 .
,
, . ,
. 7.10
, .
count 1
number_of_reports.
while.

. .
7.9 ,
.
, .
7.10.
//
// .
#1nclude <iostream>
using namespace std:

void instructlonsO;

int mai'nO
{
instructionsO:
int number_of_reports:
356 7.

7.10 {)
cout "How many conservationist reports are there? ";
c1n number_of_reports:

int grancl_total = 0. subtotal, count;


for (count = 1; count <= number_of_reports; count++)
{
cout endl "Enter the report of "
"conservationist number " count endl;
cout "Enter the number of eggs in each nest.Xn"
"Place a negative integer"
" at the end of your listAn":
subtotal = 0:
int next;
c1n next;
while (next >= 0)
{
subtotal = subtotal + next;
cin next;
}
cout "Total egg count for conservationist "
" number " count " is "
subtotal endl;
grand_total = grand_total + subtotal;
}
cout endl "Total egg count for all reports = "
grand_total endl;
return 0;
}
... instructions , 7.9. ...


,
.
,
.


40. , Hello.
41. , ;
. . ,
.
42. :
1nt . ;
for ( = 1; <= 10; ++)
for (m = 10; m >= 1; m--)
cout n " * " m
" = " n*m endl;
7.4. 357


,
. ; , .
.
, , ,
; .
< <=, ,
, , ,
.
- ,
. ,
, > < .
- ,
. doubl
,
. int ,
.
,
, . ,
, . ,
, , , .
,
( ) .
, , ,
.
, .
.
, ,
. ,
. ,
cout (
!).
.

:
int next = 2, product = 1;
while (next < 5)
{
next-H-;
product = product * next;
}
// product
// 2 5.
358 7.

, ,
, product .
, .
next product. ,
. ,
cout:
int next = 2. product = 1;
while (next < 5)
{
next++;
product = product * next;
cout "next = " next
" product = " product end!;
}
next product, ,
3. ,
3 5 2.
.
next 1, 2.
2, , ,
. -
, :
1nt next = 2. product = 1;
while (next < 5)
{
product = product * next;
next++:
}
, , next++,
. .
, , .
, ,
4, 5 .
, <=,
<. :
int next = 2. product = 1 ;
while (next <^ 5)
{
product = product * next:
next++:
}
.
.
, ,
. , ,
.
359



: ; ;
; . (
. ,
, .)

,
.

.
, .
.
, . ; ,
, , ,
,
.
,
.


, ,
.


43. ? ?
44. ?
45. 100 .
10 . ?
, ?
?

.
bool,
true false.
, true false.
1f...else
, .
360 7.


, . C++
if...else.
switch .
, , swi tch
if...else, .
,
. , , .
(
), , if...else.
for
.
,
: ;
; ;
.
,
C++. ,
.

.

.
,
, .

.

, . .



1. ) true
) true. , ), ) .
== < , &&,
, .
) , ),
.
) true
) true
361

) false. (count == 1)
false, , false,
. , ,
. C++
.
) true. (count < 10)
true, , true,
.
) false. , )
) ,
. ) :
!((true II (X < )) && true)
, , ! (true && true),
! (true), false.
) ,
, ((limit/count) > 7), .
) true. (limit < 20)
true, true,
. , , ((limit/count) > 7),
, , ,
.
C++ .
) , -
, ((limit/count) > 7), .
) false. (limit < 0)
false, false,
.
) , , .
, C++
. i nt
bool && !.
. , C++
true, - false.
(5 && 7) + ( ! 6 )

. (5 && 7)
5 7 true. true && true, true,
1. (!6) true,
(!true), false, 0.
1+0 , 1. C++
true, , , ^ , 1.

, , ,
, .
362 7.

2. ^ ,
.
1 f 1 f ...el se,
while clo...wh1le.
3. 2 < < 3 , (2<)&&(<3),
, C++.
(2 < ) < 3. (2 < ) ,
true, false, 1 ,
(2 < ) < 3 true.
.
4. . j > false ( j
-1). && ,
, ,
. ,
false .
5. bool 1n_order(1nt nl. 1nt 2. 1nt )
{
return ((nl <= 2) && (2 <= ));
}
6. bool evendnt n)
{
return ((n % 2) == 0);
}

7. bool 1s_d1git(char ch)


{
return CO* <= ch) && (ch <= ' 9 ' ) :
}

8. bool 1s_root_of(1nt root_cancl1clate, i n t number)


{ " "
return (number == root_cand1clate*root_cand1date):
}

9. Start
Hello from the second if.
End
Start again
End again

10. large

11. small

12. medium

13. start
Second Output
End

14. (x > 10) (x > 100) if...else .


, 13.
363

15. Start
100
End
16. :
i f ( < 0)
cout " is less than zero.\n";
else if ((0 <= n) && (n <= 100))
cout n " is between 0 and 100 (1nclus1ve).\n";
else if (n >100)
cout n " is larger than 100.\n";

if (n < 0)
cout n " is less than zeroAn";
else if (n <= 100)
cout n " is between 0 and 100 (inclusive).\n";
else
cout n " is larger than 100.\n";
.
17. enum ,
, .
. :
3 2 10

18. enum ,
, .
. :
2 17 5
19. Roast worms
20. Onion ice cream
21. Chocolate ice cream
Onion ice cream
( case 3 break.)
22. Bon appetit!
23. 42 22

24. ,
, . ,
, ,
. <Enter> .
{
int 1 = 1;
cout 1 endl; // l<Enter>
{
cout xl endl: // l<Enter>
int x2 = 2;
cout x2 endl; // 2<Enter>
364 7.

{
cout 2 endl; // 2<Enter>
1nt = 3:
cout endl; / / 3<Enter>
}
cout x2 endl; / / 2<Enter>
}
cout x l endl: / / l<Enter>
}
25. 2 1 0
26. 2 1
27. 1 2 3 4
28. 1 2 3
29. 2 4 6 8
30. Hello 10
Hello 8
Hello 6
Hello 4
Hello 2

31. 2.000000 1.500000 1.000000 0.500000


32. a) for;
6) while, ;
) , );
) do...wh1le, .
33. ) for ( i n t i = 1; 1 <= 10: 1++)
i f (1 < 5 && 1 != 2)
cout 'X';
6 ) for ( i n t i = 1; i <= 10; i = i + 3)
cout ' X ' ;
)cout *X'; / / , .
/ / .
for (long m = 200: m < 1000: m = m + 100)
cout ' X ' :
34. OH 1024 10.
2.
35. 1024 1. for, ,
.
36. .
: i = i * 2. i,
0.
i, 0.
37. 4 3 End of Loop.
365

38. 4 3
39. break (while, do...while for)
switch.
C++ . ,
break , .
40. for (Int count = 1; count <= 10: count++)
cout "HelloXn";
41. .
int sum = 0. next;
cout "Enter a list of even numbers. Place an\n"
"odd number at the end of the listAn";
cin next:
while ((next % 2) == 0)
{
sum = sum + next:
cin next:
}
42. , .
:
1 * 10 = 10
1*9 = 9

1*1 = 1
2 * 10 = 20
2 * 9 = 18

2*1 = 2
3 * 10 = 30

43.
.

.
44. , ,
.
45. .
:
10 = 100 /10
10 .
: 100 10
.
366 7.


1. --.
R (), (), S ().
.
: , ,
.
, .
, ,
.
2. , ,
.

, .
: $1000 1,5 %,
1 %. ,
$10; : $10
10 % . ,
, ,
.
3. .
, .
1 12.
. , ,
- , ,
, .
.
. ,
.
4. , ,
:
) 8:00 18:00 ,
40 ;
) 8:00 18:00
25 ;
) 15
.
, ,
. 24-
. ,
, char.
,
. 1 nt.
,
367

. ,
.
,

.
, .
,
. ,
.
5. , ,
, .
: I 1,V 5, X 10, L
50, 100, D 500 1000. ,
,
. , IV 4
V I, XL 40, 900 . .
: 1900, MCML ~ 1950, MCMLX - 1960,
MCMXL - 1940, MCMLXXXIX - 1989. ,
1000 3000. ,

.
6. ,
. . (
, ,
.)
. , 10 .
, 21 ,
. 21 .
1, , . ,
10 21 . ,
21. 17
27. 27 , 17.
, , 2, 3, 4
5. .
2 10, , , .
char, 2.
2 9.
, , , t, j , q, .

.
,
. .
2 21 () Busted ().
. ,
368 7.

, switch
1 f ...el se. ,
.
7. ,
, 14 % 14 %
. ,

. ,
,
. , $20 000
$1000. 10 %,
10 % .
(10 %
$20 000)/12, $166,67,
$19 166,67. (10 %
$19 166,67)/12, . . ,
.
,
. , $10 000
$1000 , $500, 5 %
$10 000. ,
-:
.
,
.
8. F^ : F^ 1, F^ 1,

= , 1,2,.... ,
. , ,
.
.
, .
.
.
,
5 . 10 ,
5 10 . 10
20 , 15 - 30 , 20 - 50 . .
,

. ,
, .
.
369


.

, ,
.
(
). ,
.
9. ^ :
1 + + /1\ + ^/! + ... + ^/\
,
1 100. ,
^, .
, , , (),
^. cmath.

.
double
(
,
).
. ,
.
8


, .


.
(+, * /),
,
.

8 . 1 .
.

, , ,
- . ., - ,
( ).
,
. .

:
6 DayOfYear, , 1
4 , ,
. ,
8.1. 371

(
23 6). 8.1 DayOfYear
equal, ,
DayOfYear .
8 . 1 .
/ / , equal. DayOfYear .
/ / 23 24 6.
finclude <iostream>
using namespace std;

class DayOfYear
{
public:
DayOfYear(int the_month. int the_day):
// : the_month the_day
// .
// .

DayOfYearO;
// 1 .

void inputO;

void outputO;

int get_month();
// : 1 . 2 - . .
int get_day();
// ,
private:
void check_date():
int month;
int day;
}:
boo! equal(DayOfYear datel, DayOfYear date2):
// : datel date2 .
// true, datel date2
// ; false.

i n t mainO
{
DayOfYear today. bach_birthday(3. 21);

'cout "Enter today's date:\n";


today. inputO;
cout "Today's date is ";
today. outputO;

cout " J . S. Bach's birthday is ";


bach_bi rthday.output();

i f ( equal(today. bach_birthday))
cout "Happy Birthday Johann Sebastian!\n";
else i^
372 8.

8.1 ()
cout "Happy Unbirthday Johann Sebastian!\n";
return 0:

bool equal(DayOfYear datel. DayOfYear date2)


{
return (datel.get_month() = date2.getjnonth() &&
datel.get_day() date2,get_day());
}
DayOfYear::DayOfYear(int the_month. int the_day)
: month(the_month). day(the_day)
{
check_date();
}
DayOfYear:iDayOfYearO : month(l). day(l)
{
// .

void DayOfYear::check_date()
{
if ((month < 1) II (month > 12) || (day < 1) || (day > 31))
{
cout "Illegal date.\n";
exit(l); // exit .
}
}
int DayOfYear::get_month
{
return month:

int DayOfYear::get_day
{
return day;
}
// iostream:
void DayOfYear::input
{
cout "Enter the month as a number:
cin month;
check_date();
cout "Enter the day of the month:
cin day;
check dateO;

// iostream.
void DayOfYear::output0
{
cout "month = " month
". day = " day endl;
8.1. 373


Enter today's date:
Enter the month as a number: 3
Enter the day of the month: 21
Today's date 1s month = 3. day = 21
J. S. Bach's birthday is month = 3. day = 21
Happy Birthday Johann Sebastian!

, today bach_bi rthday DayOfYear


, . ,
,
:
equa Utoday, bach_bi rthday)
equal true, today bach_bi rthday
. 8.1
if...else.
,
.
, , get_
month get_day.
, equal DayOf
Year. ,
, -, ,
.
, equal ,
, .


1. before,
DayOfYear, 8.1.
bool, true,
, ; false.
, 5 , 2 .


-,
,
, -. ,
-,
. equal
8.1. , -
getmonth, - get_day.
, ,
- .
374 8.

equal,
8.1, :
bool equaKDayOfYear datel, DayOfYear clate2)
{
return ( datel.month == date2.month &&
datel.day == date2.day ):
}
,
month day DayOfYear.
- ( -)
, , equal
DayOfYear. ,
, -.
, equal DayOfYear.
,
-, - .
,
. ,
. ,
8.2 DayOfYear
equal,
friend.
,
-,
, -,
friend. ,
-,
;
- .
. , equal
8.2 DayOfYear::.
.
DayOfYear, , ,
.
- -
, , -.
8.2. , ,

/ / , equal.
/ / equal DayOfYear.
#1nclude <1ostream>
using namespace std;

class DayOfYear
{
publ1 :
friend bool equaKDayOfYear datel, DayOfYear date2);
8.1. 375

// ; datel date2 .
// true, datel date2
// , false.

DayOfYeardnt the_month. 1nt the_day);


// : the_month the_day
// .
// .

DayOfYearO:
// 1 .

void inputO;

void outputO;

int get__month();
//- : 1 . 2 . .
int get_day();
// ,
private:
void check_date();
int month:
int day;
}:
int mainO
{
DayOfYear today. bach_birthday(3. 21);
cout "Enter today's date:\n";
today. inputO:
cout "Today's date is ";
today.outputO;

cout "J. S. Bach's birthday is ";


bach_bi rthday.output();

if ( equal(today, bach_birthday))
cout "Happy Birthday Johann Sebastian!\n";
else
cout "Happy Unbirthday Johann Sebastian!\n";
return 0;

bool equaKDayOfYear datel. DayOfYear date2) // - month day


// .

return (datel.month = date2.month &&


datel.day == date2.day);

DayOfYear::DayOfYear(int the_month. int the_day)


: month(the_month). day(the_day)

check_date();
iP'
376 8.

8.2 {)
DayOfYear::DayOfYear() : month(l), day(l)
{
// .

void DayOfYear::check_date()
{
if ((month < 1) II (month > 12) || (day < 1) || (day > 31))
{
cout "Illegal 1 dateAn";
exit(l); // exit .

i nt DayOfYea ::get_month()
{
return month:
}
i nt DayOfYea ::get_day()
{
return day:

// iostream.
void DayOfYear::input
{
cout "Enter the month as a number:
cin month:
check_date():
cout "Enter the day of the month: "
cin day:
check_date():
}
// iostream.
void DayOfYear::output0
{
cout "month = " month
", day = " day endl:

: ,

,
, .
-
, -
? . ,
, , -
. ,
.
8.1. 377

DayOfYear,
8.2. ,
DayOfYear. ,
,
. main :
DayOfYear today:
cout "enter today's date: \n":
today. inputO:
cout "There are " (12 - today.get_month())
" months left in this year An":
today .get_month() today .month,
month DayOfYear. ,
.
, .
. ,
, :
? . ,
equal
, ( 8.2),
, ( 8.1).
, ,
.


,
.

f ri end.
,
. ,
.

class _
{
public:
fri end ___1
friend ___2
II .
// .

__
private:
__
}:
^^
378 8.


class FuelTank
{
public:
friend double need_to_fi11(FuelTank tank);
// : - tank
// .
// ,
// , tank.
Fuel Tank (double the_capacity. double thejevel);

FuelTankO;
void inputO;
void outputO;
private:
double capacity; // ,
double level;
}:
.
.
, .

:
-,
- .
, :
.
,
. ,
-, ,
( , ,
equal 8.1).
:
- ,
;
, ; ,
. , equal ,
8.1 8.2, ,
( ).


.
, .
-
.
, . ,
8.1. 379

: -
, ,
, .
,
, .

: Money
8.3 Money,
.
, . , $9,95
995.
, , ,
double.
8.3. Money
/ / , Money.
#include <iostream>
#include <cstdlib>
#include <cctype>
using namespace std:

class Money
{
public:
friend Money addCMoney amountl. Money amount2):
/ / : amountl amount2 .
/ / amountl amount2.

friend bool equal(Money amountl, Money amount2):


/ / : amountl amount2 .
/ / true, amountl amount2
/ / : false.

Money (long dollars, int cents);


/ / ,
/ / .
/ / , dollars
/ / cents .

Money(long dollars):
// .
// $dollars.OO.

Money();
// .
// $0.00.

double get_value():
// : .
// , . ^
380 8.

8.3 ()
void input(istream& ins);
// : 1ns - ,
// . .
// -$100.00.
// : .
// Insurance.

void output(estream& outs);


// : outs - , .
// : ,
// , outs.
private:
long an_cents;

Int dig1t_to_1nt(char c);


// Money::1nput.
// : - '' '9'.
// ;
// . d1g1t_toJnt('3') 3.

int main
{
Money your_amount. my_amount(10. 9). our_amount;
cout "Enter an amount of money: ":
your_amount.1nput(c1n);
cout "Your amount 1s ";
your_amount.output(cout);
cout endl;
cout "My amount 1s ";
my_amount.output(cout);
cout endl;
If (equal(your_amount, my^amount))
cout "We have the same amounts.\n";
else
cout "One of us Is r1cher.\n";
our_amount = add{your_amount, myamount);
your_amount.output(cout);
cout " + ";
my_amount.output(cout);
cout " equals ";
our_amount.output(cout);
cout endl;
return 0;
}
Money add(Money amountl. Money amount2)
{
Money temp;
temp.all_cents = amountl.all_cents + amount2.all_cents;
return temp;
}
bool equal(Money amountl. Money amount2)
8.1. 381

{
return (amountl.an_cents == amount2.all_cents):
}
Money::Money(long dollars. 1nt cents)
{
// , .
if(dollars*cents < 0)
{
cout "Illegal values for dollars and cents.\n";
exitd);
}
all_cents = dollars*100 + cents;

Money::Money(long dollars) : all_cents(dollars*100)

// .

Money::Money : all_cents(0)

// .

double Money::get_value()

return (all cents * 0.01);

/ iostream. cctype. cstdlib.


void Money::input(istreams ins)

char one_char. decimal_point.


digitl. digit2; // , ,
long dollars;
tnt cents;
bool negative; // true,
// .

ins onechar;
if (one__char ==='-')
{
negative = true:
ins one_char: // '$'.
}
else
negative - false;
// , one_char = '$'.

ins dollars decimal_point digitl digit2;

i f (one_char != '$' || decimal_point != ' . '


II !isdigit(digitl) || !isdigit(digit2))
{
cout "Error illegal form for money inputVn";
exitd);
} ^ ^
382 8.

8.3 {)
cents =* d i g i t _ t o j n t ( d i g i t l ) * 1 0 + d i g i t _ t o J n t ( d i g i t 2 ) :
an_cents ^ donars*100 + cents;
i f (negative)
all_cents = -an_cents:
}
// cstdlib iostream.
void Money::output(ostream& outs)
{
long posit1ve_cents, dollars, cents;
posit1ve_cents = labs(all_cents);
dollars = pGsitive_cents/100;
cents = positive__cents^lOO;
if (all_cents < 0)
outs "-$" dollars '.';
else
outs "$" dollars '.';

if (cents < 10)


outs '0';
outs cents;
}
int digit_to_int(char c)
{
return ( int(c) - int('O') );
}

Enter an amount of money: $123.45
Your amount is $123.45
My amount is $10.09
One of us is richer.
$123.45 + $10.09 equals $133.54

, , -
al l_cents. int,
.
C++ i nt 2 .
, , int,
32 000, 32 000 - $320,
.
, ; $320,
- al l_cents 1 ong. ,
i nt 2 , 1 ong 4 . 1 ong
, i nt, ,

. ( long long int,
.)
Money ,
: add equal (. 8.3). Money,
8.1. 383

Money,
.
Money: equal (amountl. amount2) true,
amountl amount2 .
, Money
, $9,95 -$9,95. -
input ( 8.3), .
,
('$'), ('-'). ,
, negati ve
true. ,
. , negative
false. ,
, .
long dollars.
,
char ( ).

, i nt.
, ++
, ( :
), $7,09
09, C++ .
,
, , cents:
cents = dig1t_tojnt(digitl)*10 + digit_toJnt(digit2);

.
digit_to_int
, ' 3', i nt,
3. , -
input char
digitl digit2, .
,
digit_to_int (, '3' 3).
digit_to_int 8.3. ,
, .
, digit_toJnt( '') , digit_toJnt( ' )
1 . . , ,
, ,
.
dollars cents
, ,
( - allcents)
384 8.

. - all cents
, :
all_cents = dollars*100 + cents;
, .
, :
i f (negative)
all_cents = -an_cents:
- output ( 8.3)
- allcents.
100 . ,
all cents 995 (),
995/100, 9, 995^100, 95. ,
all_cents, 995 (), $9.95.
- output
.

C++ .
,
all cents,
labs. , abs,
, long. abs,
1 abs cstdl i b. (
C++ labs, .)

digit^tojnt
( )
digit_to_int, 8.3, :
1nt d1g1t_to_int(char )
{
return (int(c) - intCO')):
}

, .
, ' 3', ,
int,
3. 2 5, char C++
. , ' 3'
3. 1nt(c) ,
, , 1 nt. ,
, , 1 nt,
, . , 1nt('3') 3,
. (
, '3' 3). )^ 1nt(c),
.
8.1. 385

, C++ , int( '' )+1


I n t e r ) ; i n t e r )+1 1nte2'); inte2')+l intCS') . .
, . :
1nt(c) - intCO')
, . '', 1nt(c) - intCO')
1nt('0') - 1nt('0'),ToecTbO. ' 1 ' , 1nt(c) - 1nt('0') intCl') -
intCO') (1nt('0')+l) - intCO'), Int('O') - 1nt('0')+!, 1.
' 2' ' 9';
.

:
, main ,
8.3:
Money your_amount. my_amount(10. 9). our_amount:
niy_amount(10. 9) $10,09.
,09, , ,
niy_amount(10. 09), .
9 09 ,
Microsoft
, -+ 9 09
. ,
8, 10. 9
, 09 C++ . 00 07
, .
ANSI C++ ,
.
C++ GNU, g++, VC++ Microsoft
, .
,
ANSI,
. , ,
.


2. - ?
3. , Day-
OfYear, 8.2. after
DayOfYear. true,
, ;
false. , 2 ,
5 . DayOfYear,
8.2?
386 8.

4. , Money, 8.3,
subtraction .
? subtraction
Money Money,
.
5. - output Money,
8.3. Money
cout. , purse
Money,
:
purse.output(cout);
, ,
.
Money, 8.3.
- output,
. ~ ,
8.3, ,
. Money
:
purse.output(cout);

purse. outputO;
, . ,
- output , -
. outs , ,

purse.output(outs);
purse .
6. - i nput Money,
8.3. ,
. ,
,
.
. , ,
-$9.95,
$-9.95, Money
. in
put ? ,
,
?
7. :
, ,
,
. .
8.1. 387

const
, .
,
,
. , ,
,
. , 1 nt
doubl , ,
.
, , .
,
.
const,
. Money,
8.3. - add
:
class Money
{
public:
friend Money addCconst Money& amountl. const Money& amount2);
// : amountl amount2 .
//
// amountl amount2.

const
, .
Money
add:
Money addCconst Money& amountl. const Money& amount2)
{

, 8.3.
const
. ,
,
.
; ,
( ,
).
, ,
, . -
, ,
388 8.

.
( Money 8.3):
Money m;
m.1nput(c1n);

m - dll_cents
0. - input ,
. , m.1nput(c1n) ,
, .
const ,
. -,
, const.
, ,
. -
const :
class Money
{
public:
void output(ostream& outs) const:

const ,
, output :
void Money::output(ostream& outs) const
{

, 8.3.

:
const
const .
,
, . ,
, const -
, .
.
guarantee:
void guarantee(const & price)
{
cout "If not satisfied, we will pay you\n"
"double your money backAn"
"That's a refund of $"
(2*price.get_value()) endl:
}
- getvalue,
guarantee .
8.1. 389

- get_value price,
guarantee, ,
get_value (, , )
. , guarantee,
- getvalue, .
const, ,
,
, get_value,
, . , Money
const, - Money,
, ,
, . getvalue.

const
const ,
, . ( const
, .)
, . -
,
, . ,
, ,
.
- ,
, const.
, ,
. const
- .
- const,
.

class Sample
{
public:
SampleO:
friend i n t compare(const Samp1e& s i . const Sample& s2):
void inputO:
void output const:
private:
int stuff:
double more_stuff:
}:

const no .
-
, , .

8.4 Money
8.3, const , .
390 8.

- ,
const,
, 8.4.

8.4. Money
// .
class Money
{
public:
friend Money adcKconst Money& amountl. const Money& amount2);
// : amountl amount2 .
// amountl amount2.

friend bool equal (const Money& amountl, const Money& amount2):


// : amountl amount2 .
// true, amountl amount2
// ; false.

Money(long dollars, int cents);


// ,
//
/7 . ,
// dollars cents .

Money(long dollars);
// .
// $dollars.OO.

;
// .
// $0.00.

double get_value() const;


// : .
// , .

void input(istream& ins);


// : ins - ,
// . .
// .
// -$100.00.
// : .
// ins.

void output(ostream& outs) const:


// : outs - .
// .
// : ,
// , outs,
private:
long all_cents;
8.2. 391


8. - get_value
Money 8.4.
9. const:
class Money
{
public:
void input(1stream& 1ns) const;

- i nput Money, 8.4,


?
10. ,
, ? ,
:
void call_by_value(int );
void call_by_const_reference(const 1nt & x);
11. :
const i n t X = 17;
class A
{
public;
;
A(int x ) ;
i n t fOconst;
int g(const A& x);
private:
int i;
}:
const ,
. ?

8.2.
.

Bbinie , add
Money , Money
(. 8.3).
, +,
:
Money total. cost, tax;
cout "Enter cost and tax; ";
cost.input(cin);
392 8.

tax.1nput(c1n):
total = cost + tax:

,
total = addCcost. tax);

, , ;
, ,
.
, :
add(cost. tax)

:
cost + tax

,
. - , .

. , C++.


+ C++ ,
. +
add (. 8.3)
. add
, add +,
operator. 8.5
, ; ; Money
+.
8.5.
/ / , Money. (
/ / Money, 8.3 8.4.)
#1nclude <1ostream>
#inclucie <cstdl1b>
#1nclude <cctype>
using namespace std;

// .
class Money
{
public:
friend Money operator +(const Money& amountl. const Money& amount2):
// : amountl amount2 .
// amountl amount2.
friend bool operator ==(const Money& amountl, const Money& amount2);
// : amountl amount2 .
// true, amountl amount2
// ; false.
8.2. 393

Money(long dollars. 1nt cents);

Money(long dollars);

MoneyO;

double get_value() const;

void input(1stream& ins);

void output(ostreamS outs) const;


private;
long all_cents;
/* 8.4
, . */ i
}:
... , 8.3.

int mainO
{
Money costd. 50), tax(0. 15). total;
total = cost + tax;
cout "cost = ";
cost, output (cout)-;
cout endl;
cout "tax = ";
tax.output(cout);
cout endl;
cout "total bill = ";
total.output(cout);
cout endl;
if (cost = tax)
cout "Move to another state.\n";
else
cout "Things seem normal.\n";
return 0;
}
Money operator +(const Money& amountl, const Money& amount2)
{
Money temp;
temp.an_cents = amountl.all_cents + amount2.all cents:
return temp;
}
boo! operator == (const Money& amountl, const Money& amount2)
{
return (amountl.all cents == amount2.all_cents):
}

cost = $1.50
tax = $0.15
total b i l l = $1.65
Things seem normal.
394 8.

- , 8.3, ,
const
Money.
- .
Money
, ==, Money.
, amountl amount2 Money,
amount1 == amount2

,
amountl.all_cents == amount2.all_cents

, C++.
, ,
.
,
.


, +,-,/, ^ . .
. -
, .
,
operator,
(). , +
, 1.
, .
+ 11 S.5.


12. ?
13. , < ,
Money, 8.5.
Money?

14. , <= ,
Money, 8.5.
Money?

15. +
? .
8.2. 395



.
, ,
; - ,
.
,
, +,-,*,/, ^ . .
, ,
% ++
.
.
, . , * + z (*) + z,
X, Z + * .
: (.),
(::) . * ?:,
.
,
, . =
12. , [] ->,
. .



,
. ,
Money, 8.5,
:
Money base_amount(100, 60). full_amount;
fun_amount = base_amount + 25:
full_amount.output(cout):
OH :
$125.60
,
25 baseamount + 25 Money.
8.5 + ,
Money.
Money . 25
1 nt 1 ong, Money,
, Money.
, 25 $25,00,
, 1 ong.
base amount + 25
396 8.

, +
Money . ,
, ,
1 ong. , 25
Money. 1 ong
, . , ,
Money, - _ cents
2500. 25 $25,00. (
8.3.)
,
. , Money (. 8.5) ,
doubl ,
full_amount = base_amount + 25.67;

,
. ,
Money, :
class Money
{
publi :
Money(double amount);
// .
// Samount.

16.
,
, ,
+ -. ,
- .


16. ,
. Money,
8.5. :
Money; .-Money(double amount)
{


, +,
X + , C++ , -,
. ,
X = -;
8.2. 397

, ,
.
-
++, --.
, . ,
Money, 8.5,
-. Money
8.6. ,
:
Money amountl(lO). amount2(6). amounts;


amounts = amountl - amount2;

amounts ,
amountl amount2.
amounts.output(cout);
$4.00.
:
amounts = -amountl:

amounts , amountl,
. :
amounts.output(cout);

-$10.00.
++ --
-, 8.6.
,
, ++ --.
, .
8.6.
// .
class Money // Money, 8.5.
{
public:
friend Money operator +(const Money& amountl, const Money& amount2);

friend Money operator -(const Money& amountl, const Money& amount2);


// : amountl amount2 .
// amountl amount2.

friend Money operator -(const Money& amount);


// : amount .
// amount.
/ / . ^
398 8.

8.6 {)
friend bool operator ==(const Money& amountl. const Money& amount2);

/ * include ,
. * /
Money(long dollars, i n t cents):

Money(long dollars);

MoneyO;

double get_value() const;

void input(istreams ins):


void output(ostreams outs) const;
private:
long all_cents;
};
... main. ...

Money operator -(const Money& amountl. const Money& amount2)


{
Money temp;
temp.all_cents = amountl.all_cents - amount2.all_cents:
return temp;

Money operator -(const Money& amount)


{
Money temp:
temp.all_cents = -amount.all_cents;
return temp;
}
, 8.5.


, cout, ,
+ -. :
cout "Hello out there.\n";

, cout - ,
"Hello out there.\n" . .
, fout ofstream,
open,
cout fout,
, . "Hello out there.\n", ,
, . .
8.2. 399

, ,
.
Money (. 8.3-8.6)
Money - output.
,
, :
Money amount(lOO);
cout "I have " amount " in my purse.\n":

output :
Money amount(100);
cout "I have ":
amount.output(cout);
cout " 1n my purse.\n";

, ,
, :
cout amount

cout amount,
amount.
, + *, -
, 1 + 2
. cout amount?
, ,
, :
cout "I have " amount " in my purse.\n";

(, +),
( ) :
((cout "I have ") amount) " in my purse.\n":

, ,
.

(cout " I have")

, cout,
:
(cout amount) " 1n my purse.\n":

, (cout amount)
cout.
cout " in my purse.\n";

. 8.1.
, ostream.
400 8.

cout " I have " amount " in my purse.\n";

,
((cout " I have ") amount) " 1n my purse.\n":

.
(cout "I have "), cout:
((cout " I have ") amount) " in my purse.\n";

y^ "Ihave".
(cout amount) " in my purse.\n";
(cout amount), cout:
(cout amount) " 1n my purse.\n";
V ^ 1

amount.
cout " in my purse.\n";
cout " in my purse.\n", cout:
cout " in,my purse.Xn";
y^u " in my purse. \n".
cout ;
, .

. 8 . 1 .

, Money
:
class Money
{
public:

friend ostream& operator (ostreamS outs, const Moneys amount);


// : outs - ,
// .
// : ,
// , outs.

- out
put, Money.
- output.
:
ostream& operator (ostream& outs, const Money& amount)
{
8.2. 401

. . . .
Money::output, 8.3
( 1lj:ents amount. 1l_cents). ...

return outs;
}


&
ostream&. :
,
&. ,
, ,
&. ,
, .
.
, .
, ,
, . ,
, . &
, , ,
, .
,
, .
, .
:
1stream& operator (1stream& 1ns, Money& amount)
{
, . . .
Money::output, 8.3
( all_cents amount.all_cents). ...

return 1ns:


8.7, Money. output
input ,
Money.


,
C++. .
&.
.
8.7.

^
402 8.


class _
{
public:

friend istreams operator (istream& n_1.


_^ _2);
// _1 - .
friend ostreani& operator (ostream& _3,
const _^ _4):
II _3 - , .


istream& operator (istream& _1.
_& _2)
{

}'"
ostream& operator (ostream& _3.
const _& _4)
{

}"

8.7. <<
/* Money, 8.6

, 8.5 8.6.
. */

// , Money.
#include <iostream>
finclude <fstream>
#include <cstdlib>
#include <cctype>
using namespace std;

// , .
class Money
{
publi :

friend Money operator +(const Money& amountl. const Money& amount2);

friend Money operator -(const Money& amountl. const Money& amount2):

friend Money operator -(const Money& amount);

friend bool operator ==(const Moneys amountl. const Money& amount2);

Money(long dollars, int cents);

Money(long dollars);
8.2. 403

double get_value() const;

friend istream& operator (istream& ins, Money& amount);


// ,
// Money.
// -$100.00.
// : ins - ,
// .
friend ostream& operator (ostream& outs, const Money& amount);
// ,
// Money.
// Money .
// : outs - ,
// .
private:
long all_cents;

i n t dig1t_to_1nt(char ) ;
// .
// : - '' '9'.
// , ;
// . d1g1t_to_1nt('3') 3.

1nt mainO
{
Money amount;
IfStream 1n_stream;
ofstream out_stream;
1n_stream.open("1nf11e.dat");
1f (1n_stream.fail())
{
cout "Input f i l e opening f a i l e d A n " ;
exitd);
}
out_stream.open("outf11e.dat");
if (out_stream.falio)
{
cout "Output file opening failed.\n";
exitCl);

in_stream amount;
out_stream amount
" copied from the f i l e infi1e.dat.\n";
cout amount
" copied from the f i l e infile.dat.\n";

1n_streara.close();
out_stream.close();

return 0;
^
404 8.

8.7 {)
II iostream. cctype, cstdlib.
istream& operator (istream& ins, Money& amount)
{
char one_char. decimal_point.
digitl, digit2; // , ,
long dollars:
int cents;
bool negative: // true,
// .
ins one_char:
if (one_char == '-')
{
negative = true;
ins one_char; // '$'.
}
else
negative = false;
// , one__char == '$'.

ins dollars decimal_point digitl digit2;

i f (one_char != '$' || decimal_point != '."


II !isdigit(digitl) || !isdigit(digit2))
{
cout "Error illegal form for money inputXn";
exit(l):
}
cents = digit_to_int(digitl)*10 + digit_to_int(digit2);

amount.all __cents = dollars*100 + cents;


if (negative)
amount.all_cents = -amount.all_cents;

return ins;

int digit_to_int(char c)
{
return (int(c) - intCO'));

// cstdlib iostream.
ostream& operator (ostream& outs, const Money& amount)
{
long positive_cents. dollars, cents;
positive_cents = 1abs(amount.all_cents);
dollars = positive_cents/100;
cents = positive_cents^lOO;
if (amount.all_cents < 0)
outs "-$" dollars '.';
else
outs "$" dollars '.';

if (cents < 10)


8.2. 405

outs ''
outs cents;
return outs;

infile.dat outfile,dat
(He ) ( )
$1.11 $2.22 $1.11 copied from the f i l e
$3.33 infile.dat.


$1.11 copied from the f i l e i n f i l e . d a t .

-
, 8.3. 8.4, 8.5 8.6.

17. Pairs:
#include <iostream>
using namespace std;
class Pairs
{
public:
PairsO;
Pairs(int first, int second);
// .
friend istreams operator (istreams ins.
Pairs& second);
friend ostream& operator (ostreamS outs.
const Pairs& second);
private:
int f;
int s;
}:
Pairs ,
.
,
(5.6), (5,-4), (-5.4) (-5.-6).
, ,
.
18. Percent.
#include <iostream>
using namespace std;

class Percent
{
public:
friend boo! operator ==(const Percent& first.
const Percent& second);
friend bool operator <(const Percent& first.
const Percent& second);
PercentO;
Percent(i nt percent_va1ue);
406 8.

friend istream& operator (1stream& ins.


Percent& the_object);
// .
// Percent.
// : ins - .
// .

friend ostreamS operator (ostream& outs.


const Percent& a_percent);
// ,
// Percent.
// : outs - .
// ,
private:
int value;
}:
Percent , 10 %
99 %,
. ,
, % (
, 25 %).
- value int. ,
.

,
-.
,
, ,
.
, ,
.
C++ (, + ==)
.

; &,
, .



1. bool before(DayOfYear datel. DayOfYear date2)
{
return ((clatel.get_month() < clate2.get_month())
II (datel.get_month() == date2.get_nionth()
&& datel.getJayO < date2.get_day()));
407

, datel
clate2, datel
date2 , datel
date2.
2. - ,
, , .
~
,
. -
. , -
, ::.
3. DayOfYear.
. ,
, 8.2,
.
class DayOfYear
{
public:
friend bool equal(DayOfYear datel. DayOfYear date2);

friend bool after(DayOfYear datel, DayOfYear date2);


// : datel date2 .
// true, datel date2;
// false.

DayOfYeardnt the_month, int the_day);


DayOfYearO;
void inputO;
void outputO;
int get_month():
int get_day();
private:
void check_date():
int month:
int day:
}:

, after:
bool after(DayOfYear datel. DayOfYear date2)
{
return ((datel.month > date2.month) ||
((datel.month == date2.month)
&& (datel.day > date2.day))):
}
4. Money.
. ,
, 8.3,
.
408 8.

class Money
{
public:
friend Money adcKMoney amountl. Money amount2):
friend Money subtract(Money amountl. Money amount2);
// : amountl amount2 .
// amountl amount2.
friend bool equal(Money amountl. Money amount2);
Money(long dollars, int cents):
Money(long dollars);
MoneyO;
double get_value():
void input(istrearn& ins):
void output(ostream& outs);
private:
long all_cents;
}:
, subtract:
Money subtract(Money amountl. Money amount2)
{
Money temp;
temp.all_cents = amountl.alljcents - amount2.all_cents;
return temp:
}
5. Money.
. ,
, 8.3,
.
class Money
{
public:
friend Money add(Money amountl. Money amount2);
friend bool equal(Money amountl. Money amount2);
Money(long dollars, int cents);
Money(long dollars);
MoneyO;
double get_value();
void input(istreams ins);
void output(ostream& outs);
// : outs - .
// .
// :
// outs.
void output ;
// :
// .
private:
long all_cents;
409

, output,
, .
void Money::output
{
output(cout):
}

:
/ / cstdUb iostream.
void Money::output
{
long posit1ve_cents. dollars, cents;
pos1t1ve_cents = labs(all_cents):
dollars = posit1ve_cents/lOO;
cents = positive_cents^lOO:
i f (all_cents < 0)
cout "-$" dollars ' . ' ;
else
cout "$" dollars ' . ' ;

1f (cents < 10)


cout ' 0 ' ;
cout cents:
}

, - 1 nput,
purse. InputO:
,
purse.inputCcin);
,
,
Money.
6. $-9.95 -$9.95 input
onechar '$', dollars -9,
dec1mal_po1nt ' . ' , digitl d1g1t2
'9' '5'. - dollars
-9, - cents 95, :
-$9.00 $0.95, -$8,05.
, , - dollars
,
.
- 1 nput :
i f ( one_char != ' $ ' || decimal_point != ' . '
II !isdig1t(digitl) || !isdigit(digit2)
II dollars < ) //
{
cout "Error illegal form for money input\n";
exit(l);
410 8.

-
, $-0.95.
,
.
7. #1nclucle <1ostream>
using namespace std;
int mainO
{
int x;
cin x;
cout X endl;
return 0;
}

, , 077, 63.

, 77.
8. ,
8.3, const:
double Money::get_value const
{
return (all__cents * 0.01);
}
9. - 1 nput , ,
const,
.
10. : ( ) .
: ,
, .
. const int = 17; const -
*, ,
int fOconst; const ,
f .
int g(const & ); const ,
g ,
.
12. (, +, *, / . .)
.
,
. ,
operator.
13. Money.
. ,
, 8.5,
.
411

class Money
{
publ1:
friend Money operator +(const Money& amountl.
const Money& amount2);
friend bool operator ==(const Money& amountl.
const Money& amount2);
friend bool operator < (const Money& amountl,
const Money& amount2):
// : amountl amount2 .
// true, amountl amount2;
// false.

Money(long dollars, int cents);


Money(long dollars);
MoneyO;
double get_value() const;
void 1nput(1stream& 1ns);
void output(ostrearn& outs) const;
private:
long all_cents;
}:
,
<:
bool operator < (const Money& amountl.
const Moneys amount2)
{
return (amountl.all_cents < amount2.all_cents);
}
14. Money.
. ,
, 8.5,
.
class Money
{
public:
friend Money operator +(const Money& amountl.
const Money& amount2);
friend bool operator ==(const MoneyS amountl.
const Money& amount2);
friend bool operator < (const Money& amountl,
const Moneys amount2);
// : amountl amount2 .
// true, amountl amount2;
/ / false.

friend bool operator <= (const Money& amountl,


const Money& amount2):
// : amountl amount2 .
// true, amountl
// amount2; false.
412 8.

Money(long dollars. 1nt cents);


Money(long dollars);
MoneyO;
double get_value() const;
void input(1stream& ins);
void output(ostream& outs) const;
private;
long all_cents;
}:
,
<= ( <,
):
bool operator <= (const Money& amount1.
const Money& amount2)
{
return ((amountl.all_cents < amount2.all_cents)
I|(amountl.all_cents == amount2.all_cents));
}
15.
. ,
, , . ,

.
16. // cmath.
Money:;Money(double amount)
{
an_CGnts = floor(amount*100);
}
, .
, 12.34999 1234,
$12,34. ,
.
17. istreams operator(istream& ins. Pairs& second)
{
char ch;
ins ch; // ' .
ins second.f;
ins ch; // '.'.
ins second.S;
ins ch; // ' ) ' .
return ins;

ostream& operator(ostream& outs, const Pairs& second)


{
outs '(';
outs second.f;
outs '.'; // ". ".
// ,
outs second.s;
outs ' ) ' ;
413

return outs;
}

18. // iostream.
1 streams operator (istream& 1ns. Percent& the_object)
{
char percent_s1gn;
1ns the_object.value:
Ins percent_s1gn: // ( ) %.
return ins;

// Iostream.
ostream& operator (ostream& outs,
const Percent& a_percent)
{
outs a__percent.value '%':
return outs;
}


1. Money, 8.7,
:
) <, <=, > >=,
Money (. 13.);
) -; ,
Money. (
Money::.)
Money percent(Int percent_f1gure) const;
// ,
// . , percent_f1gure 10.
// 10 % , .

, purse Money, $100,10,



purse.percent(10);

10 % $100,10, Money,
$10,01.
2. 17 Pairs.
, .

1nt.
0.
+
:
(, ) + (, d)-- ( + , + d)
414 8.

-.
:
(, ) * = ( * , 6 * )
-
Pairs.
3. 18
Percent. , .

int. + -
. , *
.
-
Percent.
4. .
,
, , 1/2, 3/4, 64/2 . . ( 1/2
,
C++.) int
. Rational.
,
-
.
int, wholenumber
,
whole_number/l. , ,
, ( 0/1).
.
1/2, 15/32, 300/401 . . ,
, -1/2,
15/-32 -300/-401 . . ==, <, <=, >, >=, +, -, * /,
Rational.
.
. / //, (2 V *.
bnd , / c/d ,
a*d *.
() ,
, .
, 4/-8
-1/2.
5. . ,

+ b*i
415

( ) . doubl , i , ];
V-i. doubl ,
- real imaginary. (- imagi
nary , i.) Complex.
doubl ,
-
. ,
double, real_part
, real part +
0*1. , ,
( + 0*1).
==, + , - , * , ,
Complex. .
.
(
- double).
:
( + ( + d*i) == (* - b*d) + (a*d + *)
i :
const Complex 7'(0. 1);
.
9

,
.

,
C++ . 9.1, ,
, .
:
, ,
, ,
.
9.2 ,
2.
,
.
, ,
.
, , .

9 . 1 .
;
.

C++ ,
,
.
9.1. 417

( )
.
, .
,
(, ,
iostream cstdlib). ,
, ,
. ,
, ,
, ,
, , .
,
.


, ,
, .
.

. ,
.
.
1. - .
2. ()
- , ,
. ,
,
.

, .
3.
.
,
.
C++,
.
, , ,
, , ,
. ,
C++ ,
. , ,
, , .

.
418 9.

-
-,
. ,
,
. C++
, .

, , ,
, - ,
.


,
.
,
:
. ( ,
( , ) ,
.)

: DigitalTime

9.1 ,
DigitalTime.
, 9:30. ;
,
, pri vate: ,
.
DigitalTime
.
, -
advance, ==, . -
advance, ,

. ,
24- , ,
, 1:30 13:30.
, DigitalTime,
, -.
DigitalTime dtime.h, .h
, . ,
, .
9.1. 419

, Digital Time,
#inclucle:
#include "dtime.h"

#inclucle ,
,
, <iostream>,
, : "dtime.h".
, .
, ,
C++,
,
, ,
.
, Digital Time,
#include dtime.h.
, , ,
.
- .
, .
,
. ,
. ,
dtime.h, dtime.cpp.
,
,
C++. .,
., .,
. .,

C++. Digital Time 9.2.
,
, 9.2
, .
9 . 1 . DigitalTime
// dtime.h. DigitalTime.
// .
// 24- , 9:30 9:30
// 14:45 2:45 .
#iDelude <iostream> // istream ostream.
// ,
using namespace std:
class DigitalTime
{ x^
420 9.

9.1 {)
public:
friend bool operator (const DigitalTime& timel, const DigitalTime& time2);
// true, timel t1me2
// ; false.

Digita1Time(int the^hour, int the_minute):


// : <= the_hour <= 23 <= the_ni1nute <= 59.
// : the_hour - , the_minute - .

DigitalTimeO:
// , 0:00 ().

void advance (int niinutes_added);


// : .
// : m1nutes_added.

void advance(int hours^added, int minutes^added):


// : .
// :
// hours_added minutes_added .

friend istream& operator (istream& ins. DigitalTime& theobject);


// DigltalTime.
// : ins - ,
// .

friend ostream& operator (ostream& outs, const DigitalTime& the^object);


// DigltalTime.
// : outs - ,
// .

/* , . private
, .*/
private:
int hour;
int minute;
};

9.2. DigitalTime
// dtime.cpp. ( ,
// , ..)
// DigitalTime.
// DigitalTime dtime.h.
#include <iostream>
#include <cctype>
#include <cstdlib>
#include "dtime.h"
using namespace std;

//
// :

void read__hour(istreams ins. 1nt& the_hour);


// : 1ns
// ( 9:45 14:45).
9.1. 421

// : the_hour
// . .
// .

void read_minute(istreams ins. int& the_minute):


// ins , .
// read_hour .

int digit_to_int(char );
// : - '' '9'.
// , ; .
// digit_to_int('3') 3.

bool operator =(const Dig1tanime& timel, const DigitalTime& time2)


{
return (timel.hour == time2.hour && timel.minute == time2.minute):
}
// istream cstdlib.
DigitalTime::DtgitalTime(int the_hour, int the_minute)
{
if (the_hour < 0 || the_hour > 23 || the_minute < 0 || the_minute > 59)
{
cout "Illegal argument to DigitalTime constructor.";
exit(l);
}
else
{
hour = the_hour:
minute = the_minute;
}
}
DigitalTime: :Dig1talTime() : hour(O), niinute(O)
{
// .
}
void DigitalTime::advance(int minutes^added)
{
int gross_minutes = minute + minutes_added;
minute = gross_minutesX60;

int hour_adjustment = gross_minutes/60;


hour = (hour + hour_adjustment)^24;
}
void DigitalTime::advance(int hours_added, int minutes^added)
{
hour = (hour + hours_added)X24;
advance(minutes_added);
}
// iostream.
ostream& operator (ostream& outs, const DigitalTime& the_object)
{
outs the_object.hour ':';
i f (the_object.minute < 10) ^
422 9.

9.2 {)
outs '';
outs the_object.minute;
return outs;
}
// iostream.
istream& operator (istream& ins. DigitalTime& the_object)
{
read_hour(1ns. the_object.hour);
read_minute(1ns. the_object.minute);
return Ins;

int digit_to_int(char c)
{
return (1nt(c) - i n t C O ' ) ) ;

// iostream, cctype cstdlib.


void read_minute(istreams ins, int& the_minute)
{
char cl. c2;
Ins cl c2;
if (!(isdigit(cl) && isdig1t(c2)))
{
cout "Error illegal input to read_minute\n";
exit(l);
}
the_minute = digit_to_int(cl)*10 + digit_toJnt(c2);

i f (the_minute < 0 || the_minute > 59)


{
cout "Error illegal input to read_minute\n";
exit(l);
}

// iostream. cctype cstdlib.


void read_hour(i streams ins, int& thehour)
{
char cl. c2;
ins cl c2;
i f ( !( isdigit(cl) && (isdigit(c2) || c2 = = ' : ' ) ) )
{
cout "Error illegal input to read_hour\n";
exit(l);

if (isdlglt(cl) && c2 == ':)


{
the_hour = digit_to_int(cl);
}
else // (isdigit(cl) && isdigit(c2))
{
9.1. 423

the_hour = d i g i t _ t o j n t ( c l ) * 1 0 + digit_to_int(c2):
ins c2; / / discard ' : '
i f (c2 != ' : ' )
{
cout "Error illegal input to read_hour\n":
exit(l):

if ( the_hour < 0 || the_hour > 23 )


{
cout "Error illegal input to read_hour\n";
exit(l):
}
}

9.3. , DigitalTime
// timedemo.cpp. ( .
// , ..)
// DigitalTime.
#include <iostream>
#include "dtime.h"
using namespace std;

i n t mainO
{
DigitalTime clock, old_clock;

cout "Enter the time in 24 hour notation: ";


cin clock:

old_clock = clock:
clock.advance(15):
i f (clock == old_clock)
cout "Something is wrong.":
cout "You entered " old_clock endl;
cout "15 minutes later the time w i l l be "
clock endl:

clock.advance(2. 15):
cout "2 hours and 15 minutes after that\n"
"the time w i l l be "
clock endl:

return 0:
}


Enter the time in 24-hour notation: 11:15
You entered 11:15
15 minutes later the time w i l l be 11:30
2 hours and 15 minutes after that
the time w i l l be 13:45
424 9.


Digital Time,
#include "dtime.h"
, #1 1 ude
, . ( ,
main), , 9.3
,
Digital Time.
, ,
,
, main.
, dtime.h (. 9.1), ,
,
. ,
#inc1ude "dtime.h"

, dtime.h.
, ,
. dtime.h
, ,
, dtime.h
, #include.
, , ,
, , dtime.h .
,
. (linking),
.
. (
.)
, , . , ,
,
, , ,
.
9.1-9.3 , ,
. ,
#i ncl ude
. :
? ,
. Digital Time
,
, .
,
, Digital Time.
, .
9.1. 425

, ,
, ,
.
.
,
,

.
, ,
, . ,
,
.


9.2. ,
. , - advance
. ,
, readhour read_minute,
d1g1t_to_1nt.
.
, Digital Time (. 9.1 9.2)
- advance. ,
, ,
.

. , advance
advance (. 9.2).
hours_
added , , advance
mi nutes_added ,
.
, ,
, ,
.
, another__advance.
. read_hour readmi -
nute ,
- hour minute .
char.
, i nt,

. read_hour read_minute
, digit_to_int, ,
Money ( 8.3).
( ' 3', 3).
426 9.


-
.
.
, .
1. ,
. .h.
,
, .
, , .
2. ) ( ,
) ,
. #inc1ude ,
. ,
:
#inclucle "dtime.h"
,
. .h,
,
C++.
.
3. , main (
, . .)
, .
#1nclude , :
#include "dtime.h"
.

. ,
, ,
. (
.)


,
,
, .
,
.
,
, .
, , . , -
, , -,

.
.
9.1. 427

#ifndef
' : ,
.
. ,
, . ,
, ,
#1nclucle:
#1nclude "dtime.h"

, , ,
- . . ,
dtime.h,
finclude. C++
, . ,
,
,
. C++
, ,
. , .
DTIMEH:
#define DTIME_H

, DTIMEH
.
,
DTIMEH
. C++ ,
, DTIMEH (
), ,
. DTIMEH ,
C++,
.
, DTIMEH:
#ifndef DTIME_H

, ,
:
#endif

.
(, #1fndef #endif,
: DTIMEH ,
#endi f. #1 fndef
. if not defined . ,
#1 fdef .)
428 9.

:
#ifndef DTIMEJ
#define DTIMEJ
... ....
#endif

dtime.h,

#include "dtime.h"

.

#include "dtime.h"

DTIME_H .
, dtime.h,
#ifndef DTIME_H

,
#end1f

.
9.4 dtime.h, 9.1,
,
. dtime.h , 9.4,
,

linclude "dtime.h"

Digital Time .
9.4.
// dtime.h. DigitalTime.
// ,
// 24- , 9:30 9:30
// 14:45 2:45 .

#ifndef DTIME_H
#define DTIMEJ

finclude <iostream>
using namespace std; ,

class DigitalTime
{
... DigitalTime , 9.1. ...

}:
#endif // DTIME
9.1. 429

DTIMEH ,
,
.
, , ,
.

,
.

:

.
,
,
,
, .
,
.

1. ,
. ,
. , (
, )
:
) ;
) , ,
, ;
) ,
, ,
;
) , ,
, ;
) ,
;
) - ;
) ,
, ,
;
) ,
;
) main.
430 9.

2. .h: ,
, , ?
3. , :
. ,
, ( , )?
4. , -
.
: ,
, ?
5. , Digital Time,
9.1 9.2, ,
.
- hour minute,
minutes int,
(0:00). , 1:30
90 , 1:30 90 .
,
9.1 9.2. , ,
, .
6. C++
?

9.2.
? ,
, .

,
, ,
. , C++
. ,
.

using
std, ,
(,
1 ostream cstdl 1 b). ,
#include <iostream>
( , cin cout)
std.
( ) usi ng:
using namespace std:
9.2. 431

, , ,
, . using
std, 1 cout
, (
, ,
). cin cout
std, using ( )
,
cin cout .
-
. ,
,
using, . ,
using, ,
.
,
, ,
std.
,
? ,
( ).
^^ ,
. ,
^
, , nsl ns2,
my_function void ,
. :
{
using namespace nsl;
my_function():

using namespace ns2:


my_function():

myf unction
nsl,
ns2.
, , , ,
, , . using
, usi ng
, - . .
,
, ,
.
432 9.

nsl ,
ns2 .

(, ,
).
using , -
. ( ),
. , us1 ng
, .

using
using , ( ,
using ).
, .


,
namespace:
namespace __
{
... - . ...
}
, ,
__.
using:
using namespace __:

, , 9.5:
namespace savitchl
{
void greetingO:
}
greeting savitchl.

9.5.
#include <iostream>
using namespace s t d ;

namespace savitchl
{
void greetingO;
}

namespace savitch2
9.2. 433

void greetingO;

void big_greeting():

int mainO
{
/*
std . */

{
/*
sav1tch2. std . */
using namespace sav1tch2:
greetingO:
}

/*
savitchl, std . */
using namespace savitchl;
greetingO;

big_greeting(); return 0;
}
namespace savitchl
{
void greetingO
{
cout "Hello from namespace savitchl.\n";
}
}
namespace savitch2
{
void greetingO
{
cout "Greetings from namespace savitch2.\n";
}
}
void big_greeting()
{
cout "A Big Global Hello!\n";


Greetings from namespace savitch2.
Hello from namespace savitchl.
A Big Global Hello!
434 9.

9.5, , greetl ng
savitchl.
namespace:
namespace savitchl
{
void greetingO
{
cout "Hello from namespace savitchlAn";
}
}
,
namespace. 9.5
savitchl savitch2.
, , namespace
, .
, 9.5,
savitchl
using:
using namespace savitchl;


7. 9.5 biggreeting -
. greeting?
8. 9.5 :
void greetingCint how_many);
9. na
mespace?


: , nsl ns2,
funl,
nsl, fun2, ns2,
myf unction. (,
, .)

using namespace nsl;
using namespace ns2;
- niy_function.
- , nsl
funl, ns2 fun2.
:
using n s l : : f u n l ;
using ns2::fun2:
9.2. 435

using :
us1ng _:::
,
.
, :: . ,
9.2 :
void DigitalTime::advance(1nt hours_added. int m1nutes_added)
{
hour = (hour + hours_added)^24;
advance(m1nutes_added);
}
, advance
Digi talTime, - .
using n s l : : f u n l :
, funl nsl,
- .
, ( - , )
funl, nsl.
,
::, :
nsl::funl;
,
, .
. :
int get_number(std::istream input_stream)

get_number input_stream i stream,


std.
( std::),

using namespace std;


.


( )
using, , :
using std::cout;
using, , :
using namespace std;
.
436 9.

.
1. using (, using std: :cout:)

, using (, using namespace std;)
.
2. using (,
cout), . using
, .
, .
, nsl ns2 myfunc-
tion . :
using namespace nsl;
using namespace ns2;

, my_function
.
, :
using nsl: :my_function;
using ns2::my_function;

, myfunction
, ( ) .

10. wow void. :
speed, speedway, speed,
indy500.
. Money,
8.4 8:
void input(istream& ins);
void output(OStream& outs) const;.
,
using namespace std;
( 8.4.)


Digita ITime, 9.1 9.2,
: digittoint, readhour readmi nute.
Digital-
Time, (. 9.2).
-
Digita ITime, (
, , Digita ITime,
9.2. 437

d1git_to_1nt read_hour, read_minute).


, .

DigitalTime,
, .
(,
) ,
#include (, ).
. namespace
,
, , :
namespace
{
void samp1e_function()

} // .

, ,
.
9.6 9.7 ( )
DigitalTime. ,
(d1git_to_int, read_hour read_minute)
.
9.8,
- read__hour
.
, 9.7,
, d1g1t_to_1nt, read_hour read_minute

. , ,
(
- ).
9.6.
// dtime.h: Digital Time.
// .
// 24- , 9:30 9:30
// 14:45 2:45 .

#ifndef DTIME_H
#define DTIME_H

#include <iostream>
using namespace std;

namespace dtimesavitch
{ ^
438 9.

9.6 {)
/* namespace dtimesavitch.

dtime.cpp. */

class DigitalTime
{
... Digital Time . 9.1. ...
}:
} // dtimesavitch.

#endif //DTIMEJ

, C++,
.
.
. , ,
(
),
. ,
, . ,
,

, .
9.7.
// dtime.cpp. ( ,
// , ..)
// Digital Time.
// DigitalTime dtime.h.
#include <iostream>
finclude <cctype>
#include <cstdlib>
#include "dtime.h"
using namespace std:

// namespace .
namespace
{
//
// .
void read_hour(istream& ins. int& the_hour);
// : ins
// 9:45 14:45.
// : the_hour
// . ,
// .

void read_minute(istream& ins. int& the_minute);


// ins , .
// read_hour .

int digit_to_int(char ) :
// : - '' '9'.
9.2. 439

// , :
// , cl1git_to_1nt('3') 3.
} // .
// namespace dtimesavitch. namespace
// dtime.h.
namespace dtimesavitch
{
boo! operator ==(const D1g1talTime& timel. const D1g1talT1me& time2)
... == , 9.2. . . .
Digital Time::DigitalTime()
... , 9.2. ...

DigitalTime::DigitalTime(int the_hour, int the_minute)


... , 9.2. ...

void DigitalTime::advance(int minutes_added)


... advance , 9.2. ...

void DigitalTime::advance(int hours_added. int minutes_added)


... advance , 9.2. ...

ostream& operator (ostream& outs, const DigitalTime& the_object)


... , 9.2. .. .

II iostream .
istream& operator (istream& ins, DigitalTime& the_object)
{
// ,
// ( ).
// , .
read_hour(i ns, the_object.hour);
read_mi nute(i ns, the_object.mi nute);
return ins:
}
} // dtimesavitch
// namespace .
namespace
{
int digit_to_int(char )
. . . d1git_tojnt , 9.2. ...

void read_minute(istreams ins, int& the_minute)


. . . readjninute . 9.2. ...

void read_hour(istreams ins. int& the_hour)


. . . readjiour , 9.2. ...

} / / .

9.8.
// timedemo.cpp.
// DigitalTime.
finclude <iostream>
#include "dtime.h" J>
440 9.

9.8 ()
. . . using, . . . .
void read_hour(int& the_hour):

int ma1n()
{
using namespace std;
using namespace dtimesavitch;

int the_hour;
read_hour(the_hour): // read_hour.
// dtime.cpp (. 9.7).

DigitalTime clock(the_hour, 0). old_clock:

old_clock = clock;
clock.advance(15);
if (clock == old__clock)
cout "Something is wrong.";
cout "You entered " old_clock end!;
cout "15 minutes later the time will be "
clock endl;

clock.advance(2, 15);
cout "2 hours and 15 minutes after that\n"
"the time will be "
clock endl;

return 0;

void read_hour(int& the_hour)


{
using namespace std;
cout "Let's play a time game.Xn"
"Let's pretend the hour has just changed.\n"
"You may write midnight as either 0 or 24,\n"
"but. I will always write it as 0,\n"
"Enter the hour as a number (0 to 24): ";
cin the_hour;
if (the_hour = 24)
the hour = 0;


Let's play a time game.
Let's pretend the hour has just changed.
You may write midnight as either 0 or 24.
but I will always write it as 0.
Enter the hour as a number (0 to 24): 11
You entered 11:00
15 minutes later the time will be 11:15
2 hours and 15 minutes after that
the time will be 13:30
9.2. 441

:

-
(, ),
,
. ,
-, -,
,
.
dtimesavitch 9.7 savitch.



.
.
.
, namespace :
namespace
{
_1
_2

_
}

. 9.6-9.8.

:

.
namespace, .
,
namespace, :
namespace
{

.
( ),
.

,
(
), .
442 9.


12. , 9.8, ,
using:
using namespace dtimesavitch:

using dtimesavitch::DigitalTime;
13. :
#include <iostream>
using namespace std:

namespace sally
{
void messageO;
}
namespace
{
void messageO;

int mainO
{
messageO;
using sally::message:
messageO;
}
messageO;
return 0;
}
namespace sally
{
void messageO
{
cout "Hello from SallyAn";
}
}
namespace
{
void messageO
{
cout "Hello from unnamed An";

14. 9.7 namespace:


. na
mespace (
)? , ?
443

C++
-.
- , ,
.

- .
, ,
.
- ,
.
:
using
; using
;
::.
,
namespace .
, ,
.



1. , ), ), ),
, , )-), (
),
, main, .
2. .h .
3. .
.
4. ,
.
5. , 9.1,
- hour minute - minutes
( S ),
.
-, ,
. (
.
444 9.

read__hour, read_nii nute d1g1t_to__1nt, -



.)
,
:
istream& operator (istream& 1ns. Dig1talTime& the_object)
{
int input_hour. input_ni1nute;
read_hour(ins. input_hour);
read_minute(ins. 1nput_minute);
the_object.minutes = input_minute + 60*input_hour:
return ins;
}
, ,
. , (
), , ,
.
6. : ,
. ,
, ,
(, ),
, .
7. . big_greeting greeting,
greeting.
,
savitchl
.
void greetingO;
8. , ,
. ,
savitchl , greeting .
,
greeting
.
9. , namespace.
, savitchl:
namespace savitchl
{
void greetingO;
}

namespace savitchl
{
void greetingO
{
445

cout "Hello from namespace s a v i t c h l A n " ;

9.5.
10. void wow(speedway::speed si. IndySOO::speed s2);

11. void inputCstd::1stream& Ins);


void outputCstd::ostream& outs) const;
12. .
13. Hello from unnamed.
Hello from Sally.
Hello from unnamed.
14. , ,
. ,

,
dtlmesavltch.


1. Digital Time, 9.1 9.2,
-:
void D1g1talT1me;:1nterval_s1nce(const D1g1talT1me& a_prev1ous_t1me.
1nt& hours_1n_1nterval. 1nt& m1nutes_1n_1nterval) const

Digital Time,
(
), (
). :
D1g1talT1me current(5. 45). prev1ous(2. 30);
Int hours, minutes;
current.1nterval_s1nce(prev1ous. hours, minutes);
cout "The time interval between " previous
" and " current endl
"1s " hours " hours and "
minutes " m1nutes.\n";

, Digital Time,
:
The time Interval between 2;30 and 5:45
1s 3 hours and 15 minutes.

, , ,
. , ,
, .
Digital Time.
446 9.

2. 5,
, .
.
3. ( ) 4 8.
,
.
4. ( ) 5 8.
,
.
10

, , .

,
, .
, C++,
.

10.1.
, ,
,
. ,
, ,
.
, .
, 1nt. ,
, int,
, ,
,
. .

, . ,
, score,
, , score[0],
scoreCl], score[2], score[3] score[4]. score
, .


C++ , 1 nt, :
int score[5];
448 10.

1 nt :
score[0], scoreCl], score[2], score[3], score[4]
, ,
. .
, ,
, C++ , , 1 -
.
.
. , ,
, .
1 nt,
. doubl ,
double int.
, .
, , .
, score int.

. , :
int next. score[5]. max;
1nt (next max)
int (score).
(, score[3]) ,
int.
,
, .
, , :
int score[5]:
<1
.
,
. , score [ ]
score, score[4] .
.
,
, , . :
int = 2;
score[n+l] = 99;
score[3] 99.
score[3] score[n+l] -,
, +1
3. (score[i])
( i), , :
10.1. 449

- - , i
. , 10.1,
, .
1 0 . 1 . ,
// 5 ,
// .
#inclucle <1ostream>

int mainO
{
using namespace std:
int i, score[5], max;
cout "Enter 5 scores:\n";
cin scoreLO];
max = score[0]:
for (i = 1; i < 5; 1++)
{
cin scoreCi]:
if (score[i] > max)
max = score[i];
// max - score[0] score[i].
}
cout "The highest score is " max endl
"The scores and their\n"
"differences from the highest are:\n";
for (i = 0; i < 5; i--)
cout score[i] " off by "
(max-score[i]) endl;

return 0;
}

Enter 5 scores:
6 9 2 10 6
The highest score is 10
The scores and their
differences from the highest are:
6 off by 4
9 off by 1
2 off by 8
10 off by 0
6 off by 4

:
for
10.1 for:
for (i = 0: i < 5: i++)
cout score[i] " off by "
(max-score[i]) endl;
450 10.

.
.

:

,
.

:


, 10.1,
, .
.
,
. , 10.1,
const i n t NUMBER_OF_STUDENTS = 5;

:
i n t 1 . score[NUMBER_OF_STUDENTS]. max;

, , , 5,
NUMBEROFSTUDENTS.

: NUMBER_OF_STUDENTS
.
,
:
cout "Enter number of students:\n";
c1n number;
1nt score[number];
// HE
,
,
,
. ( 12 ,
, .)


, ,
, 1 nt doubl .
,
. .
10.1. 451

,
, . ,
:
( ,
) ,
. , (
) ,
. -
, 1 .
.
, . :
.
:
int [6]:

,
1 nt,
. [0].
- ,
[0]. ,
[3] [0], ,
,
int. . 10.1.
C++
.



_ _1_'];

_ ,
_10'] _1-
_-1']. _.

1nt b1g_array[lOO];
double [3];
double b[5];
char grade[10]. one_grade;
a [0], [1] [2] double, b
[0], [1], [2], [3] [4] .

, . , grade
one_grade.
452 10.

i n t [];

[ J

1022
1023
[0]
1024
int 1025
2 , [1]
[3] 1026
2 X 3 == 6 1027
[0]. [2]
1028
1029
[3]
1030
[6] 1031
, [4]
, 1032
. 1033
1034 [5]

[7] stuff
,
more_stuff
.

. 10.1,

:


.
:
int [6];

, ,
, 5. ,
[1 ],
1 : 0,1, 2,3,4 5. 1
) , .

,
.
.
10.1. 453

, -
.
,
, :
[1] = 238:

, 1 7. ,
[7] .
, ,
238.
[7] , , 238,
- ( ), ,
morestuf f. , ,
. . 10.1.

, .
.


.

, :
1nt ch1ldren[3] = {2. 12. 1};

:
1nt ch1ldren[3];
childrenCO] = 2:
ch1ldren[l] = 12:
ch1ldren[2] = 1;


, , .
, ,
. ,
. ,
, .
, ,
main.
, .
,

. , :
1nt b [ ] = {5. 12. 11}:

:
1nt b[3] = {5. 12. 11):
454 10.


1. int [5]; [4]
[5] [4]?
2.
double score[5]:
:
) ;
) ;
) ;
) ;
) .
3. :
) int [4] = { 8. 7. 6. 4. 3 }:
) int [] = { 8. 7. 6. 4 }:
) const int SIZE = 4:
int xESIZE];
, ?
4.
char symbol[3] ={''. 'b'. ''}:
for (int index = 0; index < 3; index++)
cout symbol[index];
5.
double a[3] = {1.1. 2.2. 3.3};
cout a[0] " " a[l] " "
a[2] endl;
a[l] = a[2];
cout a[0] " " a[l] " "
a[2] endl;
6.
int i. tempClO];
for (i = 0; i < 10; i++)
tempCi] = 2*1;
for (i = 0; i < 10; i++)
cout tempCi] " ";
cout endl;
for (i = 0; i < 10; i = 1+2)
cout temp[1] " ";
7. :
int sample_array[10];
for (int index = 1; index <= 10; index--)
sample_array[index] = 3*index;
8. ,
:
[0] < [1] < [2] < . . .
10.2. 455

, ^ , ,
- ,
. :
double [10];

... , . ...

for (int index = 0; index < 10; index--)


if (a[index] > a[index+l])
cout "Array elements " index " and "
(index+1) " are out of order.":
HO OH . ?
9. C++,
int, .
,
.
10. , :
int your_array[7];
, , C++
i nt .
? ,
_[0] ,
_[3]?

10.2.

, .
.



,
.
,
int i . . [10];

myf unction int,


my_function(n);
.
i nt,
, , :
my_function(a[3]):
456 10.

:
my_funct1on(a[i]):

1 3,
[3]. 1 , ,
:
iny_function(a[0]):

,
, .
10.2
.
.
adjust^days, old_days int.
main vacation[number]
number. , olddays
. i nt -
vacation. 10.2 .
.
10.2.
//
// .
// 5.
finclude <iostream>

const int NUMBER_OF_EMPLOYEES = 3:

int adjust_clays(int old^days);


/ / old_days 5.

int mainO
{
using namespace std;
int vacation[NUMBER_OF_EMPLOYEES]. number;
cout "Enter allowed vacation days for employees 1"
" through " NUMBER_OF_EMPLOYEES
":\n";
for (number = 1;
number <= NUMBER_OF_EMPLOYEES; number++)
cin vacation[number-l];

for (number = 0: number < NUMBER_OF_EMPLOYEES: number++)


vacation[number] = adjust_days(vacat1onCnumber]):

cout "The revised number of vacation days are:\n";


for (number = 1;
number <= NUMBER_OFJMPLOYEES; number++)
cout "Employee number " number
" vacation days = " vacation[number-l]
endl:
10.2. 457

return 0;
}

1nt adjust_days(int olcl_clays)


{
return (olcl_clays+5);
}

Enter allowed vacation days for employees 1 through 3:
10 20 5
The revised number of vacation days are: .
Employee number 1 vacation days = 15
Employee number 2 vacation days = 25
Employee number 3 vacation days = 10


. :
void t r i p l e r ( i n t & n)
{
n = 3*n;
}
:
i n t [3] = {4. 5. 6}. number = 2;
tripler(number);
tripler(a[2]);
tnpler(a[3]);
tripler(a[number]);
tripler(a):
?
12. ( - ) :
i n t b[5] = { 1 , 2. 3. 4. 5}:
for ( i n t i = 1: i <= 5; i++)
tripler(b[i]);
tripler .


.
, ,
, .
10.3,
, .
. ,
(size), ,
.
( ) ,
,
.
458 10.

10.3.

void fill_up(int ]. int size):
// : size - .
// size .
// :
// size, .

II iostream.
void fi1l_up(int []. int size)
{
using namespace std;
cout "Enter " size " numbers:\n";
for (int i = 0: i < size: i++)
cin a [ i ] :
size:
cout "The last array index used is " size endl:
}
int a[] ,
.
, ,
.
. {
, ,
[].)
fillup :
. , ,
:
int score[5]. number_of_scores = 5:
fi 1l_up(score. number_of_scores):
f 111 up score ,
. ,
[], ,
, . ( ,
.)
( , score)
.
score ?
,
. ,
fi1l_up(score. number_of_scores):
:
{
using namespace std:
size = 5: II - number_of_scores.
10.2. 459

cout "Enter " size " numbers:\n"


for (int 1 = 0; i < size; i++)
cin score[i3;
size:
cout "The last array index used is "
size endl;
}
, ,
,
. , .
score. f 11 lup
score ,
score.
, , ,
,
.
(, cin),
, .

, . -
. ,
.
, .
score:
int score[5];
,
int, .
score[0],
. ,
score[3], score[0].
, score[3]
int score[0]. score[3]
score[0] ,
, i nt;
score[3].

: ( ) ,
(, )
( ).
.

, .
, ,
,
.
460 10.

. ,
,
.
1 nt, .
,
.
, , ,
.
,
. ,
, 10.3. f 11 l_up

1 nt. , :
int score[5]. time[10]:
fillup
score , time .
fin_up(score. 5):
fni_up(time. 10):
,
,
, .

const
,
. , , ,
?

. , ,
,
.
,
.
, ,
const. , ,
.
,
, :
void show_the_world(1nt []. int s1ze_of_a)
// : s1ze_of_a - .
// .
// : .
{
cout "The array contains the following values:\n":
10.2. 461

for (int 1 = 0; 1 < s1ze_of_a: 1++)


cout a[1] " ";
cout endl:
}
show_the_world .

const:

void show_thG_world(const int d[], 1nt s1ze_of_a)

,
1: .
,
. show_the_world
. ( ,
const,
.)
void show_the_world(const'1nt []. 1nt size_of_a)
// : size_of_a - .
// .
// : .
{
cout "The array contains the following values:\n";
for (int i = 0; i < size_of_a; a[i]++) // , const
// ,
cout [1] " ";
cout endl;
}
,
const,
]; .
, [0]
.
show_the_world , for
. i
a[i ]. i
, . a[i ]++
. -
const, ; , ,
.

. const,
.
, ,
,
(. 8).
462 10.


,
: .
. ^ ,

( 0).
,
int, ( ).
, :
,
. , ,
.

_ _ (... . ___1']. . . . ) ;

void sum_array(clouble& sum. double a[]. 1nt size):

:
const
const .

, ,
.
C++ .
showdlff
computeaverage:
double compute_average(1nt []. 1nt number_used):
// number_used
// . .

void show_difference(const 1nt a[]. int number_used)


{
double average = compute_average(a, number_used);
cout "Average of the " number_used
" numbers = " average endl
"The numbers are:\n":
for (int index = 0; index < number_used: index++)
cout aCindex] " differs from average by "
(a[index]-average) endl:
}
.
computeaverage .
show_di ff , , computeaverage
.
, showdiff
10.2. 463

computeaverage, .
const, , -
teaverage .
showdifference ,
compute_average :
double compute_average(const 1nt a[], 1nt number_used);

,
,
int double.
:
. ,
, .
12.

:

. , ,
, .

Apex Plastic Spoon Manufacturing
, !
.
(
, , , . .).
,
, . ,
.
,
, .
:
Plant #1 **********
Plant #2 *************
Plant #3 **>^*^>^ ^

Plant #4

1000 .
.
,
,
,
.
464 10.


1000 ( ),
1000.
,
( 1,6 1600 ),
. , 1600
2000 .
.
. , 1 4.
; : ,
,
. ,
.
. , ,
. 1000
. ,
, 1000 .

, ,
, production. C++
0. 1 4, 3,
.
product1on[n-l]. ,
1 productionCO],
2 - product1on[l] . .
,
. , 3
4040 , production[2]
4040. 4,
4, 3
.
.
(input_data)
production[plant_number-l] (
plantnumber ) ,
.
(scale) (plant_number)
product1on[plant_number-l] ,
.
(graph) .
, ,
production.
,
10.2. 465

(
). ,
production. ,
, , ,
, 10.4.
, graph
, const.
10.4 .
,
, , .
.
, .
10.4.
// .
// .
#1nclude <1ostream>
const 1nt NUMBER_OF_PLANTS = 4;

void input_data(int a[], int last_plant_number);


// : 1ast_plant_number - .
// : plant_number = 1 last_plant_number:
// a[plant_number-l] .
// plant_number.

void scaleCint []. int size):


// : [0] a[size-l]
// .
// : a[i]
// , .
// i. <= i <= size-1.

void graph(const int asterisk_countC]. int last_plant_nuniber);


// : asterisk_count[0]
// asterisk_count[last_plant_number-l]
// .
// : , .
// N asterisk_count[N-l]
// , N.
// 1 <= N <= last_plant_number.

int mainO
{
using namespace std;
int production[NUMBER_OF_PLANTS];
cout "This program displays a graph showingXn"
"production for each plant in the company.\n":
input_data(production. NUMBER_OF_PLANTS);
scaleCproduction. NUMBER_OF_PLANTS);
graphCproduction. NUMBER_OF_PLANTS);

return 0;
466 10.

input_data
1 nputdata
10.4. ma1 ( ),
, inputdata
production,
, lastplantnumber
NUMBER_OF_PLANTS. 1 nput_data .
(plant_number) 1 last_plant_number
:
plantnumber;
;
production[plant_number-l] production.
input_data
1 nput_data
.
// iostream.
void 1nput_data(int [], int last_plant_number)
{
using namespace std;
for (1nt plant_number = 1;
plant_number <= last_plant_number; plant_number++)
{
cout endl
"Enter production data for plant number "
plant_number endl;
get_total(a[plant_number-l]);
}
}

get_total, inputdata
. gettotal, -
inputdata. ,
plant_number plantnum-
ber-1; , ,
.
gettotal.
,
, .
gettotal ,
. i nt,
. , gettotal ,
,
. ,
( ),
10.2. 467


int. , . 10.5
get_total input_clata.
.
input.data
,
. inputdata
gettotal,
gettotal.
1 nputdata ,
10.5.
1 nputdata
. , ,
, ( 4
), ( 3)
( 1 2).
, .
2 0.
10.5. input_data
// input_data.
finclude <1ostream>
const 1nt NUMBER_OF_PLANTS = 4;

void 1nput_data(1nt a[], int last_plant_number);


// : 1ast_plant_number - .
// : plant_number = 1 last_plant_nuinber:
// a[plant_number-l] .
// plant_number.

void get_total(int& sum);


//
// sum.

int mainO
{
using namespace std:
int production[NUMBER_OF_PLANTS]:
char ans;
do
{
input_data(production, NUMBER_OF_PLANTS):
cout endl
"Total production for each"
" of plants 1 through 4:\n";
for (int number = 1;
number <= NUMBER OF PLANTS; number++) iP'
468 10.

10.5 ()
cout production[number-l] " ";

cout endl
"Test Again?(Type or n and Enter): ":
cin ans;
} while ( (ans != 'N') && (ans != 'n') ) :

cout endl;

return 0;
}
// iostream.
void input_data(int a[]. int last_plant_number)
{
using namespace std;
for (int plant_number = 1;
plant_number <= last_plant_number; plant_number++)
{
cout endl
"Enter production data for plant number "
plant_number endl;
get_total(aCplant_number-l]);

}
// iostream.
void get_total(int& sum)
{
using namespace std;
cout "Enter number of units produced by each department.\n"
"Append a negative number to the end of the list.\n";
sum = 0;
int next;
cin next;
while (next >= 0)
{
sum = sum+next;
cin next;

cout "Total = " sum endl;


}

Enter production data for plant number 1
Enter number of units produced by each department.
Append a negative number to the end of the list.
1 2 3-1
Total = 6

Enter production data for plant number 2


Enter number of units produced by each department.
10.2. 469

Append negative number to the end of the list.


0 2 3-1
Total = 5

Enter production data for plant number 3


Enter number of units produced by each department.
Append a negative number to the end of the list.
2 -1
Total = 2

Enter production data for plant number 4


Enter number of units produced by each department.
Append a negative number to the end of the list.
-1
Total = 0

Total production for each of plants 1 through 4:


6 52 0
Test Again?(Type or n and Enter): n

scale
scale production,
,
. 1000 ,
production
1000.0. ,
.
, scale
10.4, ,
:
void scaleCint []. int size);
// : [0] a[size-l]
// .
// : a[i]
// , .
// i, <= i <= size-1.
scale
production, size NUMBER_OF_PLANTS,
:
scaleCproduction. NUMBER_OF_PLANTS):

scale :
for (int index = 0; index < size; index++)
a[index] 1000 ;
aCindex].

scale
scale , C++.
round,
. double
470 10.

1 nt ; ,
round .
void scalednt [], int size)
{
for (int index = 0; index < size: index++)
a[index] = round(a[index]/1000.0);
}
, 1000.0, 1000 (
). 1000, C++
. , 2600/1000 2, 2600/1000.0
2,6. ,
, 2600 3, 2,
,
.
round,
. , round(2.3) 2, round(2.6)
3. round scale 10.6.
.
round floor
cmath. ,
. f 1 (2.1), f 1 (2.9) 2.
, round ,
. round(2.4),
floor(2.4+0.5)
floor(2.9), 2.0. ,
2.0 2.5, floor 2.0,
0.5 , 3.0. ,
2.0 2.5, round 2 (
, 1 nt,
2.0
static_cast<int> 2).
, 2.5; , 2.6.
round(2.6)
floor(2.6+0.5)
f 1(3.1), 3.0. ,
2.5 3.0, floor 3.0,
0.5 , 3.0. ,
2.5 3.0, round 3.
, round
2.0 3.0. ,
. .
, round
.
10.2. 471

scale
10.6 seal ,
round seal .
, .
. ,
round (
), scale -
round. round
, , , (,
2.6), , (, 2.3).
scale
, .
10.6. scale
// scale.
#include <1ostream>
#1nclude <cmath>

void scalednt a [ ] . i n t size);


// : [0] a[size-l]
// .
// : a[i]
// , ,
// i. <= i <= size-1.

int round(double number);


// : number >= 0.
// number.
// .

int mainO
{
using namespace std;
int some_array[4]. index;
cout "Enter 4 numbers to scale: ":
for (index = 0; index < 4; index++)
cin some_array[index];

scale(some_array. 4);

cout "Values scaled to the number of 1000s are: ";


for (index = 0; index < 4; index++)
cout some_array[index] " ";
cout endl;

return 0;
}
void scale(int a [ ] , int size)
{
for ( i n t index = 0; index < size; index++)
a[index] = round(a[index]/1000.0); ^ ^
472 10.

10.6 {)

I I cmath.
1nt round(double number)
{
using namespace std:
return static_cast<int>(floor(number+0.5));
}

Enter 4 numbers to scale: 2600 999 465 3501
Values scaled to the number of 1000s are: 3 1 0 4

graph
10.7.
graph ,
.
10.7.
/ / .
/ / .
#1nclude <iostream>
#1nclude <cmath>
const i n t NUMBER_OF_PLANTS = 4;

void input_data(int a [ ] . i n t last_plant_number);


/ / : last_plant_number - .
/ / : plant_number = 1 last_plant_number:
/ / a[plant__number-l] .
/ / plant_number.

void scalednt [ ] . i n t size);


// : [0] a[size-l]
// .
// : a[i]
// , .
// 1. <= 1 <= s1ze-l.

void graph(const int asterisk_count[], int last_plant_number);


// : asterisk:_count[0]
// asterisl<_count[last_plant_number-l]
// .
// : , .
// N asterisk_count[N-l]
// , N.
// 1 <= N <= last_plant_number.

void get_total(int& sum);


//
// sum.

int round(double number);


// : number >= 0.
// number.
// .
10.2. 473

void print_asterisks(int n);


// .

int mainO
{
using namespace std;
int production[NUMBER_OF_PLANTS]:
cout "This program displays a graph showingXn"
"production for each plant in the company.\n";
i nputjata (producti on. NUMBER_OF_PLANTS);
scaleCproduction. NUMBER_OF_PLANTS);
graphCproduction. NUMBER_OF_PLANTS);
return 0;

// iostream.
void input_data(int a[]. int last_plant_number)

... inputjdata 10.5. ...

// iostream.
void get_total(int& sum)

... get_total 10.5. ...

void scalednt , int size)

... scale 10.6. ...

// cmath.
int roundCdouble number)

... round 10.6. ...

// iostream.
void graphCconst int asterisk_count[], int last_plant_number)
{
using namespace std;
cout "\nUnits produced in thousands of units:\n";
for (int plant_number = 1; plant_number <= last_plant_number: piant_number-H-)
{
cout "Plant #" plant_number " ";
print_asterisks(asterisk_count[piant_number-1]);
cout endl;
}
}
// iostream.
void print_asterisks(int n)
{
using namespace std;
for (int count = 1; count <= n; count++)
cout "*";


This program displays a graph showing
production for each plant in the company.
474 10.

Enter production data for plant number 1


Enter number of units produced by each department.
Append a negative number to the end of the list.
2000 3000 1000 -1
Total = 6000

Enter production data for plant number 2


Enter number of units produced by each department.
Append a negative number to the end of the list.
2050 3002 1300 -1
Total = 6352

Enter production data for plant number 3


Enter number of units produced by each department.
Append a negative number to the end of the list.
5000 4020 500 4348 -1
Total = 13868

Enter production data for plant number 4


Enter number of units produced by each department.
Append a negative number to the end of the list.
2507 6050 1809 -1
Total = 10366

Units produced in thousands of units:


Plant #1 ******
Plant #2 ******
Plant #3 ***************
Plant #4 "^ir*********


13. onemore,
int
. -
, .
14. :
void too2(int [], int how_many)
{
for (int index = 0; index < how_many; index--)
a[index] = 2:
}
:
int my_array[29];
too2(my_array. 29);
too2(my_array. 10);
too2(my_array. 55);
"Hey too2. Please, come over here."
int your_array[100];
too2(your_array. 100);
too2(my_array[3]. 29);
?
10.3. 475

15. const ,
:
void output(double []. int size);
// : [0]
// a[size-l] .
// : [0] a[size-l].

void drop_odd(int []. int size):


// : [0]
// a[size-l] .
// : [0]
// a[size-l] .
16. outof order,
int double,
size int. ,
,
[0] <= [1] <= [2] <= ...

, ,
. ,
-1. :
double [10] = {1.2. 2.1, 3.3. 2.5. 4.5. 7.9. 5.4. 8.7. 9.9. 1.0}:

[2] [3] ,
, [3] - ,
out_of_order 3.
, -1.

10.3.
, ,
.

,
.
C++, ,
.


,
, ,

.
,
476 10.

. ,
, .

,
,
, . 10.8.
, , ,
.
, .
score, ,
, .
numberused.
score[0] score[number_used-l].
, numberused
. ,
,
. ,
,
, .
showdifference computeaverage.
flllarray ,
, ,
.
10.8.
//
// .
#1nclude <1ostream>
const 1nt MAX_NUMBER_SCORES = 10;

void f n i _ a r r a y ( i n t a [ ] . i n t size. int& number_used);


// : size - .
// : number_used
// . [0] a[number_used-l]
// , .

double compute_average(const int a[]. int number__used);


// : [0] a[number_used-l]
// ; number_used > 0.
// [0] a[number_used-l].

void show_difference(const int a[]. int number_used);


// : number_used a .
// :
// number_used .

int mainO
{
using namespace std;
10.3. 477

i n t score[MAX_NUMBER__SCORES]. number_used;

cout "This program reads golf scores and shows\n"


"how much each differs from the average.\n";

cout "Enter golf scores:\n";


fill_array(score. MAX_NUMBER_SCORES. number_used);
show_difference(score. number__used);

return 0:

// iostream.
void f i l l _ a r r a y ( i n t a [ ] . i n t size, int& number_used)
{
using namespace std;
cout "Enter up to " size
" nonnegative whole numbers.\n"
"Mark the end of the list "
"with a negative number.\n";

int next, index = 0;


cin next;
while ((next >= 0) && (index < size))
{
a[index] = next;
i ndex++;
cin next;

number used = index;

double compute_average(const int a[]. int number_used)


{
double total = 0;
for (int index = 0; index < number_used; index+--)
total = total+aCindex];
if (number_used > 0)
{
return (total/number_used);
}
else
{
using namespace std;
cout "ERROR: number of elements "
"is 0 in compute_average.\n"
"compute_average returns 0.\n";
return 0;
}
}
void show_difference(const int a [ ] . i n t number_used)
{ ^
478 10.

10.8 ()
using namespace std;
double average = compute_average(a. number_used);
cout "Average of the " number_used
" scores = " average endl
"The scores are:\n";
for (int index = 0: index < nuniber_used; index++)
cout a[index] " differs from average by "
(a[index]-average) endl;
}


This program reads golf scores and shows
how much each differs from the average.
Enter golf scores:
Enter up to 10 nonnegative whole numbers.
Mark the end of the list with a negative number.
69 74 68 -1
Average of the 3 scores = 70.3333
The scores are:
69 differs from average by -1.33333
74 differs from average by 3.66667
68 differs from average by -2.33333

:

fillarray 10.8.
score MAX_NUMBER_SCORE$,
:
fill_array(score. MAX_NUMBER_SCORES. number_used):

MAX_NUMBER_SCORES , fill^array
. :
. fin_array
10.8,
MAX_NUMBER_SCORES.
, ,
. , 10.9,
.
. f i 1 l a ray
MAXNUMBERSCORES,
10.9.
f i 1 l_array ,
.
MAX_NUMBER_SCORES ,
.
10.3. 479

:

. , ,
, . ,
, , .
10.9
. ,
,
.
.

.
10.9.
//
// .
#1nclude <1ostream>
const int DECLARED_SIZE = 20;
void fill_array(1nt a[]. 1nt size. int& number_used);
// : size - .
// : number_used
// .
// [0] a[number_used-l]
// , .
int search(const int [], int number_used, int target);
// : number__used <== a.
// [0] aCnumber_used-l] .
// , a[index] = target.
// ; -1.
int mainO
{
using namespace std;
int arr[DECLARED_SIZE]. list_size. target:
fil1_array(arr. DECLARED_SIZE. list_size):
char ans;
int result;
do
{
cout "Enter a number to search for: ";
cin target;
result = searchCarr, list_size, target);
i f (result = -1)
cout target " is not on the list.Xn";
else
cout target " is stored in array position "
result endl
"(Remember: The first position is 0.)\n"; ^
480 10.

10.9 ()
cout "Search again?(y/n followed by Enter): ";
Gin ans:
} while ((ans 1- 'n') && (ans I 'N'));

cout "End of program.\n":


return 0;
}
// iostream.
void fin_array(int a[], int size, int& number_used)
... f1ll_arrdy 10.8. ...

int searchCconst int [], int number_used. int target)


{
int index = 0;
boo! found = false:
while ((!found) && (index < number^used))
if (target =* a[index])
found = true:
else
index++:

if (found)
return index:
else
return -1:
}

Enter up to 20 nonnegative whole numbers.
Mark the end of the list with a negative number.
10 20 30 40 50 60 70 80 -1
Enter a number to search for: 10
10 is stored in array position 0
(Remember: The first position is 0.)
Search again?(y/n followed by Enter):
Enter a number to search for: 40
40 is stored in array position 3
(Remember: The first position is 0.)
Search again?(y/n followed by Enter):
Enter a number to search for: 42
42 is not on the list.
Search again?(y/n followed by Enter): n
End of program.

10.9 search.
, .
, ,
.
search ,
, -1.
10.3. 481

. while,

. found , ,
. , found true while
.

:

,
-
. sort,
.
,
, numberused,
. :
void sortCint []. int number_used):
// : number_used <=
// .
// [0] a[number_used-l]
// .

sort :
[0] < [1] < [2] < ... :^ a[number_used-l]
, ,
.
.
.
.
, , [0]
, [1] . . ,

( [index]):
for (int index = 0; index < number_used: index++)
. ,

, , .
sort
, , .
. ,
.
, , . 10.2.
[0] .
[3]. [0] [3].
[1],[2],[3],... ,[9]
482 10.

. [5],
[1]. ];
, . .
, ,
. ,
, [9].
, [9] .
,
, [9], ,
.

[0] [1] [2] [3] [4] [5] [6] [7] [8] [9]
1 8 1 6 1 10 \ 1 16 1 4 18 14 12 20 1

^
^
6 1 10 16 1 4 18 14 12 20 1
\ |:^::^^^^:^^^'^--^^i:
_>
v_
1^:-:2;:::-| 1 10 1 8 16 1 4 18 14 12 20 1

<" ~~\
1 2 1 1 10 1 8 16 1 4 18 14 12 20 1
^
"^

1 2 1 4 1 10 1 8 16 1 6 18 14 12 20

. 10.2.

10.10 sort
.
index_of_smallest,
, ,
. swap_val ues (
4), 10.10. ,
swap__values(a[0]. [ 3 ] ) :

[0] [3].
10.10.
/ / sort.
#1nclucle <1ostream>

void f1ll_array(1nt a [ ] . 1nt size. 1nt& number_used):


// : size - .
// : number_used .
10.3. 483

// [0] a[number_used-l]
// , .

void sortdnt ], int number_used);


// : number_used <= .
// [0] aCnumberused-l] .
// : [0] a[number_used-l]
// ,
// [0] <= 1] <= ... <= aCnumber_used-l].

void swap_values(int8i vl. int& v2);


// vl v2.

int index_of_smallest(const int a[].


int startjndex. int number_used);
// : 0 <= startjndex < number_used.
// ' a[start_index] a[number_used-l]
// .
// i a[i].
//
// a[start_index]. a[start_index+l] a[number_used-l].

int mainO
{
using namespace std;
cout "This program sorts numbers "
"from lowest to highest.Xn";
int sample_array[10]. number_used:
fill_array(sample_array. 10. number_used):
sortCsamplearray, numberused):

cout "In sorted order the numbers are:\n";


for (int index = 0; index < number_used; index++)
cout sample_array[index] " ";
cout endl:

return 0;

// iostream.
void fill_array(int a[]. int size, int& number_used)

. . . fil]_array 10.9. ...

void sort(int []. int number_used)


(
i nt i ndex_of_next_smal1 est;
for (int index = 0; index < number_used-l; index++)
{// a[index] :
i ndex_of_next_smal1 est =
index_of_smanest(a, index, numberused);
swap_va1ues(a[index], a[index_of_next_sma11est]);
// a[0] <= a[l] <=...<= a[index] -
// .
// .
}
} ^
484 10.

10.10 {)
void swap_values(1nt& v l . 1nt& v2)
{
int temp;
temp = vl:
vl = v2:
v2 = temp;

int index_of_smallest(const int a[].


int start index, int number_used)
{
int min = a[start_index],
index_of_min = startjndex;
for (int index = start_index+l;
index < number_used; index++)
i f (a[index] < min)
{
min = a[index];
index_of_min = index;
// min -
// a[start_index] a[index].

return index_of_min;
}

This program sorts numbers from lowest to highest.
Enter up to 10 nonnegative whole numbers.
Mark the end of the list with a negative number.
80 30 50 70 60 90 20 30 40 -1
In sorted order the numbers are:
20 30 30 40 50 60 70 80 90


17. ,
number_array .

.
18. ,
. ,
abed.
:
dcba
, ,
. 1etter_box.
.
19. search,
10.10.
10.4. 485

bool search (const 1nt a [ ] . i n t number_usecl,


1nt target, int& where);
// : number_used <=
// a.
// [0] a[number_used-l] .
// : target - [0]
// a[number_used-l],
// true where
// , a[where] == target;
// false,
// where .


,
.

10.4.
, , ,
, ,
. ,
.


, ,
, . ,
,
. ,
, :
(, , ).
:
struct Windlnfo
{
double velocity; // .
char di'recti on: // 'N'. 'S'. 'E' ' W .
}:
Windlnfo data_po1nt[10]:
datapoint, for:
Int 1;
for (1 = 0; 1 < 10; 1++)
{
cout "Enter velocity for "
1 " numbered data point:";
cin data_point[1].velocity;
cout "Enter direction for that data point"
" (N, S. E. or W): ":
cin data_point[1].direction;
}
486 10.

data_point[1].velocity
. data_point - , data_po1nt[1]
1, W1 ndlnfo
-: velocity direction. , data_point[i] .velo
city - velocity i-ro data_
poi nt. i - . data_poi nt [i ]. di -
paction i-ro .
, datapoint,
for:
for ( i = 0; i < 10; i++)
cout "Wind data point number " i ": \ n "
data_point[i].velocity
" miles per hour\n"
"direction " data_point[i].direction
endl:
10.11 Money.
. -
, - Money
8.3-8.7 13 8.
. ,
Money .
Money .
10.12.
, ,
. ,
, , ,
. 10.12
10.1 , 10.12
.
1 0 . 1 1 . Money
// money.h. Money.
// .
lifndef M0NEY_H
#def1ne M0NEY_H
#1nclucle <1ostream>
using namespace std;
namespace moneysavitch
{
class Money
{
public:
friend Money operator +(const Money& amountl. const Money& amount2);
// amountl amount2.
friend Money operator -(const Money& amountl, const Money& amount2);
// amountl amount2.
friend Money operator -(const Money& amount):
// amount, .
10.4. 487

friend boo! operator =(const Money& amountl, const Money& amount2):


// true, amountl amount2
// ; false.

friend boo! operator


< (const MoneySt amountl, const Money& ainount2);
// true, amountl amount2,
// false .

Money(long dollars, int cents);


// ,
//
// . ,
// dollars, cents .

Money(long dollars);
// .
// $dollars.OO.

;
// .
// $0.00.

double get_value() const;


// .
// .

friend istreams operator (istream& ins. Money& amount):


// .
//
// Money.
// -$100.00.
// : 1ns - ,
// .

friend ostream& operator


(ostream& outs, const Money& amount);
// .
//
// Money.
// Money
// .
// : outs - ,
// ,
private:
long all_cents:
}:
} // moneysavi'tch.
#end1f // MONEYJ

, ,
(int double). , ,
difference, :
Money d1fference[5];
for (1 = 0; i < 5; i++)
d1fference[1] = max-amount[i];
488 10.

10.12. ,
// 5 ,
// .
#include <1ostream>
frinclude "money.h"

1nt mainO
{
using namespace std:
using namespace moneysavltch;
Money amount[5]. max;
int 1;

cout "Enter 5 amounts of money:\n";


c1n amountCO];
max = amount[0]:
for (1 = 1; 1 < 5; 1++)
{
c1n amount[1];
1f (max < amount[1])
max = amount[1];
// max -
// amount[0] amount[1].
}

Money d1fference[5];
for (i 0; i < 5; i++)
differenceCi] = max-amount[i];

cout "The highest amount 1s " max endl;


cout "The amounts and the1r\n"
"differences from the largest are:\n":
for (1 = 0; 1 < 5; 1--)
{
cout amount[1] " off by "
d1fference[1] endl:
}
return 0:
}

Enter 5 amounts of money:
$5,00 $10.00 $19.99 $20.00 $12.79
The highest amount Is $20.00
The amounts and their
differences from the largest are:
$5.00 off by $15.00
$10.00 off by $10.00
$19.99 off by $0.01
$20.00 off by $0.00
$12.79 off by $7.21
10.4. 489


20. Score -
home_teani opponent 1 nt. game
Score.
, .
21. , ,
.
Money.
. ,
10.12, .


.
, -
. my_best Data (
)
:
struct Data
{
double time[10];
int distance;
}:
Data my_best;
mybest : distance int,
, time double
.
20 , :
my_best. distance = 20;
, :
cout "Enter ten times (in seconds):\n":
for (int i = 0; i < 10; i++)
cin my_best.time[i];
my_best.time[i] : my_best - ; my_best.ti
me - time. my_best.time
, . , my_best. ti -
me[i] i- mybest.time. |^
, ,
- ,
. .

:

10.13 10.14 TemperatureList,
.
490 10.

TemperatureList , .
- 1 i st, .
,
- size.
11 st,
.
, ,
include:
#inclucle "tempiiSt.h"
TemperatureList .
,
TemperatureList my_clata;
mydata TemperatureList.
TemperatureList
. - size
my_data , , .
, - addtemperature
( - list):
my_data.add_temperature(77);
my_data,
1 i St . ,
add_temperature ,
, , .
10.13. -
// tempiist.h.
//
// TemperatureList.
// .

#ifndef TEMPLIST_H
#clefine TEMPLIST_H
linclude <1ostream>
using namespace std;
namespace t l i s t s a v i t c h
{
const int MAX_LIST_SIZE = 50:

class TemperatureList
{
public:
TemperatureListO:
// .

void add_temperature(double temperature):


// : .
10.4. 491

// :
// .

bool full const;


// true, .
// false .

friend ostream& operator


(ostream& outs, const TemperatureL1st& the_object);
// .
//
// TemperatureList.
// .
// : outs - .
// .

private:
double list[MAX_LIST_SIZE]; // .
int size; // .
};
} // tlistsavltch.
#endif // TEMPLIST

10.14. -
// TemperatureList (tempiist.).
// TemperatureList tempiist.h.
#include <iostream>
#include <cstdlib>
#include "tempiist.h"
using namespace std;
namespace tlistsavitch
{
TemperatureList::TemperatureList() : size(O)
{'
// .

void TemperatureList::add_temperature(double temperature)


{// iostream cstdlib.
if ( fulK) )

cout "Error: adding to a full list.\n";


exit(l);

else

list[size] = temperature;
size = size+1;

^
492 10.

10.14 ()
bool TemperatureList::full() const
{
return (size == MAX LIST SIZE):

// lostream.
ostream& operator
(ostream& outs, const TemperatureL1st& the_object)
{
for (int 1 = 0; 1 < the_object.s1ze; 1++)
outs the_object.list[i3 " F\n":
return outs;
}
} / / t U s t s a v i t c h .

TemperatureList .
:
, ,
. ,
mydata,
cout my_clata;

TemperatureList .
,
. :
my_data = TemperatureLlstO;

TemperatureList ,
.
doubl .
, ,
double ,
.
10.


22. TemperatureList, 10.13 10.14,
- get_s1ze,
.
23. TemperatureList, 10.13 10.14,
- gettemperature Int,
MAXLISTSIZE.
double, .
,
1 . . ,
, .
10.5. 493

10.5.
, .

C++ .
.


, C++ .
:
char page[30][100];

page, :
29 99.
, , [0][0], [15][32],
[29][99]. ,
. ,

.
,
. ,
, . ,
page :
[0][0], [0][1] [0][99]
[1][0]. [1][1] [1][99]
[2][0]. [2][1] [2][99]

[29][0]. [29][1] [29][99]


30 ( 29) 100 (
99).
C++ page .
,
30 ,
100 . , ,

. , .
^
.
494 10.



_1_[._2']... [__'];

char page[30][100]:
int matrix[2][3];
double three_d_p1cture[lO][20][30]:

. ,
:
matr1x[0][0]. matr1x[0][l]. matr1x[0][2],
matr1x[l][0], matr1x[l][l], matr1x[l][2]



30 ,
100 .
char page[30][100]:
: , C++
, .
:, ,
page, :
void clisplay__page(const char p[][100], 1nt s1ze_d1mens1on_l)
{
for d n t indexl = 0;
Indexl < s1ze_d1mens1on_l: indexl++)
{// :
for (int 1ndex2 = 0; 1ndex2 < 100: index2++)
cout p[1ndexl][index2];
cout endl;
}
}
,
,
int. ( ,
. ,
.) ( , )
, :
const char [][100]
, - ,
.
const char [][100]
10.5. 495

,
.
,
100 , .


,
, ( )
. int.
.
void get_page(char [][100]. int sl2e_d1mension_l);

: ,

10.15
. , grade.
, . . 10.3 ,
. ,
. ,
,
. , 4 1
grade[3][0] grade.

10.15.
// , .
// grade ( ,
// , ).
//
// . .
#111 <1ostream>
#1nclude <1omanip>
const 1nt NUMBER_STUDENTS = 4. NUMBER_QUIZZES = 3;

void compute_st_ave(const i n t graded[NUMBER_^QUIZZES], double st_ave[]);


// : NUMBER_STUDENTS
// NUMBER_QUIZZES grade.
//
// grade[st_num-l, quiz_num--l]
// st_num qu1z_num.
// :
// st_ave[st_num-l]
// stu_num.

void compute_quiz_ave(const int grade[][NUMBER_QUIZZES], double quiz_ave[]);


// : NUMBERSTUDENTS
/ / NUMBER_QUIZZES grade. ^
496 10.

10.15 ()
//
// grade[st_num-l. quiz_num-l]
// st_num quiz_num.
// :
// quiz_ave[quiz_num-l]
// quiz_num.

void displayCconst int grade[][NUMBER_QUIZZES].


const double st_ave[]. const double qu1z_ave[]):
// : NUMBER_STUDENTS
// NUMBER_QUIZZES grade.
//
// grade[st_num-l. quiz_num-l]
// st_num qu1z_num.
// st_ave[st_num-l]
// stu_num.
// quiz_ave[quiz_num-l]
// quiz_num.
// : grade. st_ave
// quiz_ave .

int mainO
{
using namespace std;
i nt grade[NUMBER_STUDENTS][NUMBER_QUIZZES];
double st_ave[NUMBER_STUDENTS];
double quiz_ave[NUMBER_QUIZZES]:

... . , .

compute_st__ave(grade. st_ave);
compute_quiz_ave(grade. quiz_ave):
displayCgrade. st_ave. quiz_ave):
return 0;
}

void compute_st_ave(const int grade[][NUMBER_QUIZZES]. double st_ave[])


{
for (int st_num = 1; st_num <= NUMBERJTUDENTS; st_num+H-)
{// st_num:
double sum = 0;
for (int qui2_nuin = 1;
qui2_num <= NUMBER_QUIZZES: qu1z_num++)
sum = sum+grade[st_num-13[quiz_num-l];
// sum st_num,
st_ave[st_num-l] = sum/NUMBER_QUIZZES;
// st_ave[st_num-l]
// st_num.
}

void compute_quiz_ave(const int grade[][NUMBER_QUIZZES], double quiz_ave[])


10.5. 497

for (int quiz_num = 1:


qu1z__num <= NUMBER^QUIZZES: qu1z_nuni++)
{// ( ):
double sum = 0;
for (int st_num = 1;
st_num <= NUMBERJTUDENTS: st_num++)
sum = sum+'grade[st_num-l][quiz_num-l]:
// sum quiznum.
quiz_ave[quiz_nunbl] = sum/NUMBER_STUDENTS;
// quiz_ave[quiz_num-l]
// quiz_num.

// iostream iomanip.
void d1splay(const int grade[][NUMBER_QUIZZES].
const double st_ave[]. const double quiz_ave[])
{
using namespace std:
cout.setf(ios::fixed);
cout.setf(ios::showpoint):
cout.precision(l):

cout setw(lO) "Student"


setw(5) "Ave"
setw(12) "Quizzes\n":
for ( i n t st_num = 1;
st_num <= NUMBERJTUDENTS; st_num++)
{ / / st_num:
cout setw(lO) st_num
setw(5) st_ave[st_num-l] " ";
for ( i n t quiz_num = 1;
quiz_num <= NUMBER_QUIZZES: quiz_num++)
cout setw(5)
grade[st_num-l][quiz_num-l];
cout endl;

cout "Quiz averages = ";


for ( i n t quiz_num = 1;
quiz_num <= NUMBER_QUIZZES; quiz_num++)
cout setw(5) quiz_ave[quiz_num-l];
cout endl;

( )
Student Ave Quizzes
1 10.0 10 10 10
2 1.0 2 0 1
3 7.7 8 6 9
4 7.3 8 4 10
Quiz averages = 7.0 5.0 7.5
498 10.

f' Teem ^1
1 grade[0][0] grade[0][l] grade[0][2]
^
2 grade[l][0] grade[l][l] grade[l][2]
*^
3 grade[2][0] grade[2][l] grade[2][2]
4 grade[3][0] grade[3][l] grade[3][2]

r \
^


4 1
^'

'

4 2
11

4 3

. 10.3. grade

,
. st_ave .
, st_ave[0]
1, st_ave[l] 2 . .
quizave . , quiz_ave[0]
1, quiz_ave[l]
2 . . . 10.4
grade, st_ave qu1z_ave,
grade. ,
st_ave quiz_ave.

1 2 3
1 10 1n 10 10.0 st_ave[0]
iu

2 2 0 1 1.0 st_ave[l]
3 8 6 9 7.7 st_ave[2]
4 8 4 10 7.3 St ave[3]

qu1z_ave
1. 1
7.0 5.0

7.5

. 10.4. grade, st_ave quiz_ave

grade,
10.15.
499

.

- ,
, .
, .

:
, 10.15
grade : -
cle[st_nuin-l][quiz_num-l].
, : grade[st_num-l.
quiz num-l], C++ . C++
, , , ,
.


24. :
1nt my_array[4][4]. indexl. 1ndex2;
for (indexl = 0: indexl < 4; indexl++)
for (index2 = 0; index2 < 4; index2++)
my_array[indexl][index2] = index2;
for (indexl = 0; indexl < 4: indexl++)
{
for (index2 = 0; index2 < 4; index2++)
cout niy_array[indexl][index2] " ":
cout endl;
}
25.
, .
( ,
).
int [4][5]:
26. void echo ,
echo(a. 4):
- 25 ,
( ).

.
,
, .
for
.
500 10.


. ,
.

, , ,
.
,
.
, (
0).
1 nt, .

int
.
,
, const.
.
,
- .
, ,
, .



1. int [5]; .
[4] ,
. 4,
, .
2. ) score;
) double;
) 5;
) 4;
) score[0], score[l], $core[2], score[3], score[4].
3. a) ;
) , 4;
) , 4.
4. .
5. 1.1 2.2 3.3
1.1 3.3 3.3
501

(, , .)
6. 2 4 6 8 10 12 14 16 18
4 8 12 16

7. sample_array samp1e_array[0] ... sample_array[9],


sample_array[l] sample_ar-
[10]. 10 .
8. . 1 ndex
9, 1ndex+l 10, a[index+l]
[10],
. ,
for:
for (int index = 0: index < 9; index++)

9. int i. a[20];
cout "Enter 20 numbers:\n";
for (i = 0 : i < 20; i++)
cin a[i];

10. 14 . _[3]
1006.
. :
tripler(number):
tripler(a[2]);
tripler(a[number]);
:
tripler(a[3]);
tripler(a):

,
. tripler ,
. ,
,
. , ,
.
12. [1] [5], 5
. , 1, 2, 3 4.
:
i n t b[5] = { 1 . 2. 3. 4. 5};
for ( i n t i = 0; i < 5; i++)
tripler(b[i]);

13. void one_more(int a [ ] . i n t size)


// : size - .
// [0] a[size-l] .
// :
// a[index] 1.
{
for (int index = 0; index < size; index++)
502 10.

[index] = a[1ndex]+l;
}

14. :
too2(my_array. 29):
too2(my_array. 10);
too2(your_array. 100):

too2(my_array. 10):
, _.
, .
:
too2(my_array. 55);
"Hey too2. Please, come over here."
too2(my_array[3]. 29);
,
.
, :
, , too2
. ,
,
.
15. output ,
.
drop_odd ,
.
void output(const double a[]. 1nt size);
// ; [0]
// a[s1ze-l] .
// ; [0] a[s1ze-l].

void drop_odd(1nt []. 1nt size);


// : [0]
// a[s1ze-l] .
// ; [0] a[s1ze-l]
// .

16. Int out_of_order(double array[]. Int size)


{
fordnt 1 = 0; 1 < s1ze-l; 1++)
If (array[1] > array[1+l]) // a[1+l] 1.
return 1+1;
return -1;
}
17. #1nclude <1ostream>
using namespace std;
const Int DECLARED_SIZE = 10;
Int maInO
503

cout "Enter up to ten nonnegative integers.\n"


"Place a negative number at the end.\n";
int number_array[DECLARED_SIZE]. next, index = 0:
cin next;
while ( (next >= 0) && (index < DECLARED_SIZE) )
{
number_array[index] = next;
i ndex++;
cin next;
}
int number_used = index;
cout "Here they are back at you:";
for (index = 0; index < number_used; index+-b)
cout number_array[index] " ";
cout endl;
return 0;

18. finclude <iostream>


using namespace std;
const int DECLARED_SIZE = 10;
int mainO
{
cout "Enter up to ten letters"
" followed by a period:\n";
char letter_box[DECLARED_SIZE]. next;
int index = 0;
cin next;
while ( (next != '.') && (index < DECLAREDJIZE) )
{
letter_box[index] = next;
i ndex++;
cin next;
}
int number_used = index;
cout "Here they are backwards:\n";
for (index = number_used-l; index >= 0; index--)
cout letter_box[index];
cout endl;
return 0;

19. bool search(const int a[]. int number_used.


. int target. int& where)
{
int index = 0;
bool found = false;
while ((!found) && (index < number_used))
if (target == a[index])
found = true;
else
i ndex++;
// target ,
// found == true a[index] == target,
if (found)
where = index;
return found;
504 10.

20. struct Score


{
int home_team;
1nt opponent:
}:
Score game[10]:
21. // 5 ,
// .
#1nclude <1ostream>
#1nclude "money.h"
int ma1n()
{
using namespace std;
Money amount[5];
i nt i:
cout "Enter 5 amounts of money:\n";
for (i = 0: i < 5; i++)
cin amount[i];
for (i = 0; i < 5; i++)
amount[i] = amount[i]+amount[i];
cout "After doubling, the amounts are:\n";
for (i = 0; i < 5; i++)
cout amount[i] " ";
cout end! ;
return 0;
}
( 2*amount[i], *
Money.)
22. , .

namespace tlistsavitch
{
class TemperatureList
{
public:
TemperatureListO:

int get_size() const;

// .

void add_temperature(double temperature);

double get_temperature(int position) const;


// : 0 <= position < get_si2e().
//
// . 0.
bool full const:

friend ostream& operator (ostreamS outs.


const TemperatureList& the_object):
505

private:
double list[MAX_LIST_SIZE];// ,
int size; // .
}:
} // tlistsavntch.
,
10.13, .
, -:
int TemperatureList::get_size() const
{
return size;

// iostream cstdlib.
double TemperatureList::get_temperature (int position) const
{
if ( (position >= size) || (position < 0) )
{
cout "Error:"
" reading an empty list position.Xn";
exit(l);

else
{
return (list[position]);
}
}
23. C M . 22.
24. 0 12 3
0 12 3
0 12 3
0 12 3

25. int aC4][5];


int indexl. index2;
for (indexl = 0; indexl < 4; indexl++)
for (index2 = 0; index2 < 5; index2++)
cin a[indexl][index2];

26. void echo(const int a[][5]. int size_of_a)


// size_of_a lines
// 5 .
{
for (int indexl = 0; indexl < size_of_a; indexl++)
{
for (int index2 = 0; index2 < 5; index2++)
cout a[indexl][index2] " ";
cout endl;
506 10.


1 6 ( 6
.) 7-10
. 11-14
,
, (
).
1. , .
1 ( -). ,

, ,
, 12 .

, 12

. , . .
. 12
, ,
12 12 .
.
.
, 1 12,
.
switch. - -
, .
,
,
12 .
, 10.7, ,
,
.
,
: ,
. ,
,
, , .
2 ( ).
,
.
. ,
,
5.
507

3 ( -). ,
, .

, ,
, .
2. delete_repeats,

. ,
: 1 nt,
.
, .
. ,
,
,
.
:
char [10];
[0] = ''
[1] = '-
[2] = '-
[3] = ''
int size = 4;
delete_repeats(a. size);
[0] '',
[1] '', [2] '', size
3. ( [3] ,
.) ,
.
.
3.
. ,
,
, , . 5
N X. :

N
X - ^ ^, ^.... ,

.
: i nt,
. double.
.
,
i nt.
508 10.

, .
, .
49 .

. ,
.
.
, :
-12 3 -12 4 1 1 -12 1 -1 1 2 3 4 2 3 -12
:
N Count
4 2
3 3
2 2
1 4
-1 1
-12 4

5. .
, .
, ;>
,
.
, .

.
,
.
, .
.
. ,
,
,
.
,
:
[0] [1] [2] [3] [4] [5] [6] [7] [8] [9]
8 6 10 2 16 4 18 14 12 10
, [0] ( 8),
. .
:


[0] [1] [2] [3] [4] [5] [6] [7] [8] [9]
8 6 10 2 16 4 18 14 12 10
509

[1] (
6). ,
. ,
[0][1].
:
-

[0] [1] [2] [3] [4] [5] [6] [7] [8] [9]
6 8 10 2 16 4 18 14 12 10

, .

, [2],
, . [2]
(
),
. :


[0] [1] [2] [3] [4] [5] [6] [7] [8] [9]
6 8 10 2 16 4 18 14 12 10

[3].
,
[3] , :


[0] [1] [2] [3] [4] [5] [6] [7] [8] [9]
6 8 10<---.->2 16 4 18 14 12 10


[0] [1] [2] [3] [4] [5] [6] [7] [8] [9]
6 8<-- -->2 10 16 4 18 14 12 10


[0] [1] [2] [3] [4] [5] [6] [7] [8] [9]
< -->2 8 10 16 4 18 14 12 10


[0] [1] [2] [3] [4] [5] [6] [7] [8] [9]
2 8 10 16 4 18 14 12 10

,
,
.
510 10.

6.
. , 1234
: [0] 1, [1] - 2,
[2] 3 [3] 4.
:
4 - [0], 3 - [1], 2 - [2] 1 - [3].
,
20 .
char, , ,
1234 ' , '2', '3' '4'.
1nt. ,

. ( .
,
.)
,
.
20 , .
20 ,
.

. ,
,
.
7. ,
.
.
struct,
. , .
,
do be do bo.

:
Letter Number of Occurrences
3
d 2
b 2
e 1

,
.
sort, 10.10.
. : -
,
.
1 511

8. -
: , ( ),
, ( ), (
, ),
( , ), ( ),
( ), (
).
. :
. ,
,
.
9. .
, ,
: , ,
. , .
.
.
- Money ( 10.11). ,
.
, , ,
.
, ,
( ).
.
.
,
,
, . , : ,
,
.
.
10. List double.
TemperatureList, 10.13
10.14, ,
. ,
double. ,
22 23. - ,
.
- getlast,
.
, . -, deletejast,
. void.
,
- size. delete_last
512 10.

, .
,
TemperatureList 10.15 10.16. ,
List.
. -,
.
:
1 2 3
4 5 6
7 8 9

, ,
.
:
XX
4 5 6
0 8 9

12. .
, :
1 D
2 D
3 D
4 D
5 D
6 D
7 D

, X
, . , -
1, 2 4 :
1 X D
2 D
3 D
4 X D
5 D
6 D
7 D


, . ,
. ,
,
. ,
.
13. ,
10.7.
, , , .
.
513

14. .
,
.
, .
.
(
) .
,
. ,
, ,
, 80 22 .
, .
,
. .
, .
.
.
, ,
.
, ,
, .
,
.
.
,
,
(,
).
. ,
.
char 80 22
.
, .
, .

. .
514 10.

. , ;,
.
. ,
.
.
. generation void,
world 80 22
char. ,
.
, :
, .
display, world
. generation display
.
Enter.
.
11

: , ?
: , , .

, :
. ,
.
11.1 11.2 ,
. char,
,
'\0'. , C++
. , ,
, . ,
, "Hello", C++ .
ANSI/ISO C++
string. ,
.
,
.
, C++,
, .

1 1 . 1 .
.

,
C++ . , -
C++.
516 11.



char. , "Hel 1"
: "Hel 1"
'\0', . '\0' -
,
-.
, . ,
, .
C++ - ' \0',
, , '\',
. ,
char char.

- ' \ 0 '
- '\0' , .
. -
, , char
char.

. , ,
"Hello", ,
.
. ,
:
char s[10];
,
, .
-
'\0', .
.
,
, . ,
.
1 nt.

'\0'.
, s "Hi Mom!",
:
SCO] s[l] s[2] s[3] s[4] s[5] s[6] s[7] s[8] s[9]
1 I 0 m 1 \0 7 ? 1
11.1. 517

' \ 0 ' ,
. , s[0], s [ l ] ,
s[2] . ., ' \ 0 ' , , .
,
, ,
.
:
- ' \ 0 ' .
, , ,
, .
,
:
char my_messdge[20] = "Hi there.";
, , ,
.


,
. , .

char _[___ + 1 ] ;

char my_c_stringCll]:
, - ' \0',
. , mycstring
.

, . C++
, ,
(
' \ 0 ' ) . ,
char short_str1ng[] = "abc";

char short_str1ng[4] = "abc";
:
char short_str1ng[] = "abc":

char short_string[] = { ' a ' , ' b ' . ' c ' } ;


. ' ' ' \ 0 ' ,
( ' \0' ' ' ,
- ).
518 11.

,
, . ,
:
char our_string[5] = " H i " ;
,
: our_string[0], our_string[l], our_string[2], our_string[3] our_string[4].
:
int index = 0;
while (our_string[index] != '\0')
{
our_string[index] = 'X';
index++;
}
, ourstring,
, ' X'.


,
:
char niy_string[] - "Do Be Do";
'\0'.
, ,
. ,
my_string (
"Do Be Do" - '\0').


, ' \0' - ,
,
. ,
char happy_string[7] = "DoBeDo";
happy_string[6] = ' Z ' :
happystring , .
happystri ng -
"DoBeDo", -,
( 'Z').
- ' \0'
.
while, ourstring.
, ' \ 0 ' ,

. while :
i n t index = 0;
while ( (our_string[index] != ' \ 0 ' ) && (index < SIZE) )
11.1. 519

{
our_string[index] = 'X';
1ndex++:
}
' \0'
.
SIZE ,
our_string.

: = ==


, C++ . ,
.
==, ,
. , .
,
C++. , :
char a_str1ng[lO];
a^string = "Hello";
.

, .

char happy_string[7] = "DoBeDo";
, , .
,
strcpy:
strcpy(a_str1ng, "Hello");
a_str1ng "Hello". ,
strcpy ,
.
C++ ,
strncpy ( ). ,
. :
char another_string[10];7
strncpy(another_str1ng, a_string_var1able. 9);
a_string_va-
riable ( ) another_string.

( ==).
520 11.

.
, ,
.
strcmp. :
if (strcmp(c_str1ngl, c_string2))
cout "The strings are NOT the same.";
else
cout "The strings are the same.";
, strcmp -
true, .
,
c_stringl c_string2,
.
c_stringl c_string2,
. , strcmp
0.
{) . ,
.
, strcmp ,
,
, .

1 f ,
true, false. ,
, .
C++, ANSI/ISO,
strcmp ,
.
strcpy strcmp
<cstring>.
:
#inclucle <cstring>
( ) :
using namespace std;
.

cstring
include
using.
cstring. ,
,
#include <cstring>
11.1. 521

cstring

<cstring> . 11.1.

#1nclude <cstr1ng>

strcpy strcmp, ,
cstring, , :
using namespace std;
.
strlen,
. , strlenC'dobedo") 6,
"dobedo" .
strcat ; ,
,
. .
, , ,
. :
char str1ng_var[20] = "The rain";
strcat(Str1ng_var. "1n Spain");
OH str1ng_var, "The ralnln
Spain". ,
( rain In, , ).
. 11.1, , , ,
+4- strcpy, strcat strcmp.
(strncpy, strncat strncmp).

1 1 . 1 .
cstring

51 ( _. ,
) ,
,
_
_

Strncpy(_. strcpy,
, ) ,


strcpy.
C++
^
522 11.

11.1 ()

11(_. ,
) ,
,
_
_

St meat (_, streat,


, ) ,

street.

C++
St1en() ,
,
(- '\0'
.)
St(rpo/<5_i. 2) , _1 _1 _2
_2 . ,
,
, _1 false.
, _2\ ,
, ,
_1 ,
_2.



$1{_1. stremp,
_2. ) ,


stremp.
C++


,
, .
,
, 1 nt,
.
, ,
(
) . ,
, - '\0'.
11.1. 523


1. :
char string_var[10] = "Hello";
char string_var[10] = {''. ' e ' . ' 1 ' . ' 1 * . ' ' . ' \ 0 ' } :
char str1ng_var[lO] = {'H'. 'e'. '1'. ' V , 'o'};
char string_var[6] = "Hello";
char str1ng_var[] = "Hello";
?
2. s1ng1ng_str1ng
:
char sing1ng_str1ng[20] = "DoBeDo":
strcat(s1nging_str1ng. " to you"):
,
, #include cstring.
3. ( - ) :
char str1ng_var[] = "Hello";
strcat(string_var. " and Good-bye.");
cout str1ng_var
,
, #1riclude cstring.
4. , strlen, ,
, . .
- ,
, .
5. ,
, :
char s[6];
.
6.
:
) ' ;
);
) "";
) "";
) "\".
7. char,
, :
char short_str1ng[] = "abc";

char short_str1ng[] = { 'a', 'b'. 'c'};
524 11.

8.
:
char our_str1ng[l5] = "Hi there!";
, ' X',
.
9. (SIZE -
):
char our_str1ng[SIZE];
ourstring .
:
i n t index = 0;
while (our_string[index] != ' \ 0 ' )
{
our_string[index] = 'X';
i ndex++;
}
. ' X',
. .
?
, .
10. , "Hello"

.
char a_string[10]:
,
.
11. :
char song[10] = "I did it ";
char franks_song[20];
strcpy ( franks_song. song );
strcat ( franks_song, "my way!");
cout franks_song endl:
, ,
.
12. ( ) :
char a_string[20] = "How are you? ";
strcat(a_string. "Good. I hope.");


.
, .
. :
cout news " Wow.\n";
news .
11.1. 525

, ,
: ,
, .
,
. :
char [80]. [80];
cout "Enter some input:\n";
c1n a b;
cout a b "END OF OUTPUTXn";

C++, :
Enter some input:
Do be do to you!
DobeEND OF OUTPUT

a b :
"Do", , b
"be", .
,
, ,
. , -, , -,

. -
getHne, : cin,
. getline .
, , ,
.
,
, .
:
char [80];
cout "Enter some input:\n";
c1n.getl1ne(a. 80);
cout a "END OF OUTPUTXn":

:
Enter some input:
Do be do to you!
Do be do to you!END OF OUTPUT

cin.getline . ,
, .
:
char short_string[5];
cout "Enter some input:\n":
cin.get1ine(short_string. 5):
cout short_string "END OF OUTPUTNn":
526 11.

^
.
Enter some Input:
dobedowap
dobeEND OF OUTPUT
, short_str1ng
, , 5.
, ' \ 0 ' . ,
.
1 cout
. cin
, ,
cout , .
( - 5.)

getline
- getl 1
.

_. getl 1 \{_.
__ + 1);
_
_. __
, , .
( , - '\0',
, _
.)

char one_line[80];
c1n.getl1ne(oneJ1ne. 80);
( , .)


13. (
):
char [80]. [80];
cout "Enter some 1nput:\n";
cin a b;
cout a -' b "END OF OUTPUT\n":
:
Enter some input:
The
time is now.
?
11.1. 527

14. (
):
char my_string[80];
cout "Enter a line of i n p u t : \ n " :
c1n.getl1ne(my_string. 6);
cout rny_str1ng "<END OF OUTPUT";
:
Enter line of input:
May the hair on your toes grow long and curly.
?


"1234" 1234 .
, .
, ,
C++, .
, , ,
1234, "1234". ,
, "1234", "1.234".
,
, . ,
,
, ,
, ,
. .
,
, .
,
atol.
-
1nt, . , atoi ("1234")
1234. , 0.
, ("#37") , ("#37")
. . alphabe
tic to integer ( --). atoi
<cstdl1b>, ,
, :
#1nclude <cstdl1b>

int,
long. atol,
, ato1, .
11.1 readandclean,
,
528 11.

' ' ' 9'. atoi


. ,
readandclean
, .
.
, ,
, :
1 nt, ,
.
1 1 . 1 .
/ / read_ancl_clean.
#include <1ostream>
#include <cstdl1b>
#1nclude <cctype>

void read_and_clean(int& n);


/ / . , .
/ /
/ / .

void newJineO:
// .
// '\' .

int mainO
{
using namespace std:
int n;
char ans:
do
{
cout "Enter an Integer and press Enter: ";
read_and_clean(n):
cout "That string converts to the integer "
n end!;
cout "Again? (yes/no): ";
cin ans;
newJineO;
} while ( (ans != 'n') && (ans != 'N') );
return 0;
}
// iostream. cstdlib cctype.
void read_and_clean(int& n)
{
using namespace std;
const int ARRAYJIZE = 6;
char digit_string[ARRAY_SIZE];
char next;
cin.get(next);
int index = 0 ;
while (next != '\n')
11.1. 529

{
if ( (isdigit(next)) && (index < ARRAY_SIZE - 1) )
{
digit_string[index] = next;
index++:
}
cin.get(next);
}
d1git_str1ng[index] = ' \ 0 ' ;

n = atoKdigitstring):

/ / lostream.
void newJineO
{
using namespace std;

... newji'ne 5,6.


Enter an integer and press Enter: $ 100
That string converts to the integer 100
Again? (yes/no): yes
Enter an integer and press Enter: 100
That string converts to the integer 100
Again? (yes/no): yes
Enter an integer and press Enter: 99^
That string converts to the integer 99
Again? (yes/no): yes
Enter an integer and pfess Enter: 23X &&5 *12
That string converts to the integer 23512
Again? (yes/no): no

readandclean, 11.1,
, ,
,
.
, .
, .
11.2 readandclean ,
geti nt, , ,
, ,
. . ( geti nt
,
5.6.)
readandclean 11.1 getint 11.2
.
3 ,
getint, double, int.
530 11.

, double.
atof
cstdlib. , atof("9.99")
9.99 double. ,
double, 0.0.
. alphabetic to floating point
( --). ,
-
.


atoi, atol atof ,
, .
. , atoi
1nt, atol long. atof
doubl . ,
, ,
0. ,
1nt X = atoi("657");

657,
double = atof("12.37"):
12.37.
, atoi, atol atof,
:
#include <cstdl1b>

11.2.
//
// get_1nt.
#include <iostream>
#include <cstdl1b>
#1nclude <cctype>

void read_and_clean(1nt& n):


// . , .
// ^ .

void newJineO:
// .
// '\' .

void get_1nt(1nt& 1nput_number):


// 1nput_number ,
// .

int mainO
11.1. 531

using namespace std;


int input_number;
get_i nt(i nput_number);
cout "Final value read in = " input_number endl;
return 0;
}

// iostream read_and_clean.
void get_int(int& input_number)
{
using namespace std;
char ans;
do
{
cout "Enter input number: ";
read_and_clean(i nput_number);
cout "You entered " input_number
" Is that correct? (yes/no): ";
cin ans;
newJineO;
} while ((ans != 'y') && (ans !- 'Y'));
}

// iostream. cstdlib cctype.


void read_and_clean(int& n)
{

... read_and_clean ILL

II iostream.
void newJineO
{

... newjine 5.6.


Enter input number: $57
You entered 57 Is that correct? (yes/no): no
Enter input number: $77*5xa
You entered 775 Is that correct? (yes/no): no
Enter input number: 77
You entered 77 Is that correct? (yes/no): no
Enter input number: $75
You entered 75 Is that correct? (yes/no): yes
Final value read in = 75
532 11.

11.2. string
,
: !

11.1 ,
, ' \0'.
. ,
, ,
, . ,
,
. .
C++ ANSI/ISO , string,

. .

string
string <str1ng>
std.
:
#1nclude <str1ng>
using namespace std;
stri ng stri ng
, . ,
string =,
- +. , si, s2 s3
string si s2 .
s3 , si,
s2, :
S3 = s i + s2;

.
, s3 .
si s2 s3,
.
,
C++ ,
stri ng.
string, string.
,
S3 = "Hello Mom!":

s3 string,
, "Hello Mom!".
11.2. string 533

string ,
stri ng . ,
, .
string ,
, apiyMCHT. :
string phrase;
string nounC'ants");
phrase,
. noun,
, "ants".
, noun "ants", .
.
"ants" , string. noun
string, ,
"ants", - '\0'.
,
- .
string
. :
string nounC'ants");
string noun = "ants";
.
string ,
11.3. , string
.
11.3. string
/ / s t r i n g .
#1nclucle <1ostream>
#include <string>
using namespace std;

1nt maInO
{
string phrase; // .
// ,
string adjectiveC"fried"). noun("ants");
string wish = "Bon appetite!";
phrase = "I love " + adjective + " " + noun + "!";
cout phrase endl
wish endl;

return 0;
}

I love fried ants!
Bon appetite!
534 11.

11.3:
phrase = "I love " + adjective + " " + noun + "!";

, C++
. "I love " string.
( -).
" I 1 ove " +, C++
"I love ".
: string
, string ,
( string). ,
string.

. , C++
string, "I love " string,
+.
.
+ .

string
string ,
, , 11.1.
string,
std. , ,
( ) :
#include <string>
using namespace std;
string ,
string , ,
string
. :
string s i . s2("Hello");

string ,
.
C++ .

- string
string ,
, .
, 11.3.
.
string ,
, , ,
11.2. string 535

, .
:
string s i . s2;
cin s i :
cin s2;

May the hair on your toes grow long and curly!
si "May" ,
s2 "the". ,
, , .
, .
,
string, getline.
,
11.1 . ,
ci .getl i ne, getl i ne (
- cin) cin
.
string line;
cout "Enter a line of input:\n";
getl1ne(cin. line);
cout line "END OF OUTPUT\n";
,
:
Enter some input;
Do be do to you!
Do be do to you!END OF OUTPUT
,
, getline.
getline string. cin
, .

- string
string
cout, cin.
string ,
, .
, getline.

string greetingC"Hello"), response. next_word;
cout greeting endl;
getlineCcin. response):
cin next word;
536 11.

cin .
dn.get, 5.
char, string,
stri ng. 11.4 ,
getline cin.get string.
new_l i ne :
cin getline .
11.4. , string
/ / getline cin.get.
finclude <iostreafTi>
#include <string>

void newJineO;

int mainO
{
using namespace std:
string first_name, last_name. record_name;
string motto = "Your records are our records.";

cout "Enter your f i r s t and last name:\n";


cin f1rst_name last_name;
newJineO:

record_name = last_name + ". " + first_name;


cout "Your name in our records is: ";
cout record_name endl:

cout "Our motto is\n"


motto endl;
cout "Please suggest a better (one line) motto:\n":
getline(cin. motto):
cout "Our new motto will be:\n":
cout motto endl;

return 0;

// iostream.
void newJineO
{
using namespace std;
char next_char;
do
{
cin.get(next_char);
} while (next char != ' \ n ' ) ;


Enter your first and last name:
'Elanna Torres
11.2. string 537

Your name in our records 1s: Torres, 'Elanna


Our motto IS
Your records are our records.
Please suggest a better (one-line) motto:
Our records go where no records dared to go before.
Our new motto will be:
Our records go where no records dared to go before.


15. , :
string s i . s2;
cout "Enter a line of input:\n";
cin si s2:
cout si "*" s2 "<END OF OUTPUT";
:
Enter line of input:
A string is a joy forever!
?
16. , :
string S;
cout "Enter line of input:\n":
getlineCcin. s):
cout s "<END OF OUTPUT";
:
Enter line of input:
A string is a joy forever!
?

:
getiine
getiine:
string l i n e ;
cout "Enter a line of input:\n";
getlineCcin. line);

, ' \'.
,
. , getl i ne
:
string l i n e ;
cout "Enter some i n p u t : \ n " ;
getline(cin. l i n e . ' ? ' ) ;

, ,
.
538 11.

getline void,
,
cin.
string s i . s2;
getlineCcin. s i ) s2;
si , s2 -
( ).
getl ine(ci . si) ci ,

cin s2;
getline , ,
.

:
cin getline
,
cin getline,
. :
i n t :
string Itne;
cin n;
getlineCcin. l i n e ) ;

:
42
Hello hitchhiker.

, 42,
line , "Hello hitchhiker.".
42,
1 i - . ?
ci ; ,
, ' \'.
getline (
).
' \' , .
,
, , getline .
new_l i ne,
11.4, ignore iostream. :
cin.ignoredOOO. '\');

- ignore
, ' \' ( 1000 ,
'\').
11.2. string 539

getline string
getline string:
1stream& getl1ne(1stream& ins. string& str_var. char delimiter);

istream& getline(istream& ins. string& str_var):
i stream,
( cin),
strvar string , delimiter.
, .
delimiter '\'.
.
getline (
cin), void.

getl 1
.
. ,
,
cin.get.

string
string ,
11.1, , .
,

, ,
.
string lastname, -
last_name[i].
11.5.
- 1 ength,
stri ng, .
, string
,
.
11.5. string
// string .
#include <iostream>
#include <string>
using namespace std:

int mainO
{ ^
540 11.

11.5 {)
string first_name. last_name;

cout "Enter your first and last name:\n";


cin f1rst_name last_name;

cout "Your last name is spelled:\n";


1 nt 1;
for (1 = 0 ; 1 < last_name.length(); 1++)
{
cout last_name[i] " ":
last_name[i] = '-':
}
cout endl;
for (1 = 0 : 1 < last_name.length(); i++)
cout last_name[i] " "; // "-" ,
cout endl;
cout "Good day " f1rst_name endl;
return 0;
}

Enter your first and last name:
John Crichton
Your last name is spelled:
C r i c h t o n

Good day John

stri ng ,
.
( , ),

, .
string - at,
. , , ,
-, ( a[i ] . at(i)), -
, , , ,
. i a.at(i) ,
, .

, (
):
string str("Mary");
cout s t r [ 6 ] endl:
a :
string str("Mary");
cout s t r . a t ( 6 ) endl;

. ,
.
11.2. string 541

string
char , s t r [ i ] .
- at. ,
str string 'X'
:
str.at(2)='X';

Str[2]='X';

, string
, 2.
- stri ng . 11.2.
,
, 11.1. , ==,
string, ,
true,
, false
. <, >, <=, >=
. ( ()

ASCII, 3. ,
, ,
.)

string
string C++ ==, !=, <, >, <=,
>= .
, (. 11.1).

11.2. - string

string :
string
string "); string ""
string string ,
(_);
^ (_
string)

\_']
i -.

^
542 11.

11.2 {)

, dti'i) i
-.
,
7[1]
.substri, ) ,
,
/
!
! = 2'. 2
2
! += 2: !
true,
. 1{) , false
,
! + 2 ! 2
2 ,
.inserti, !)-.
,
. remove( . ):

! == 2 .
! != 2 bool
! <= 2 .
! >= 2

.f1nd{!) !

.fintiiCTpoKa!. ) !
;
.f1nd_f1rst_of(!.
) !;

.f1nd_f1 St j]ot_of(!.
) ,
!;

:
- , .
, 11.6, ,
, .
11.2. string 543


. :
Able was I ere I saw Elba.
I Love Me. Vol. I .
Madam. I'm Adam.
A man, a plan, a canal. Panama.
Rats l i v e on no evil star.
radar
deed
mom
racecar

remove_punct , -
substr find string. - substr
, .
remove_punct .
for, s
punct.
- f 1 nd. punct,
no_punct.

11.6.
// , .
#include <1ostream>
#include <str1ng>
#1nclude <cctype>
using namespace std:

void swap(char& vl. char& v2);


// vl v2.

string reverse(const string& s):


// s , .

string remove_punct(const strings s. const string& punct):


// s,
// punct.

string make_lower(const strings s);


// s.
// , .

bool is_pal(const string& s):


// true, .
// false .

i n t mainO
{
string s t r ;
cout "Enter a candidate for palindrome test\n"
"followed by pressing Enter.\n"; ^
544 11.

11.6 {)
getlineCcin, s t r ) ;

if (is_pal(str))
cout "\"" str + "\" is a palindrome.";
else
cout "\"" str + "\" is not a palindrome.":
cout endl:

return 0;
}

void swap(char& vl. char& v2)


{
char temp = vl;
vl = v2;
v2 = temp;
}

string reverse(const string& s)


{
int start = 0:
i n t end = s.lengthO;
string temp(s);

while (start < end)


{
end--;
swap(temp[start]. temp[end]);
start++;

return temp;
}

// cctype string,
string make_lower(const strings s)
{
string temp(s);
for (int i = 0; i < s.lengthO; i++)
temp[i] = tolower(s[i]);

return temp;
}

string remove_punct(const strings s. const strings punct)


{
string no_punct: // .
i n t s j e n g t h = s.lengthO:
i n t punctjength = punct.lengthO:
11.2. string 545

for (int i = 0; 1 < sjength; i++)


{
// s.
string a_char = s.substr(i,l);
// s punct.
int location = punct.find(a_char, 0);

if (location < 0 || location >== punctjength)


no_punct = no_punct + a_char; // a_char
// punct. .
}
return no_punct;

/ / makejower. remove_punct.
bool 1s_pal(const str1ng& s)
{
string punct(".;:.?!'\" " ) ; // .
string str(s);
str = makejower(str);
string lowGr_str = remove_punct(str. punct);

return (lower str == reverse(lower s t r ) ) ;


Enter a candidate for palindrome test
followed by pressing Enter.
Madam, I'm Adam.
"Madam. I'm Adam." is a palindrome.

Enter a candidate for palindrome test


followed by pressing Enter.
Radar
"Radar" Is a palindrome.

Enter a candidate for palindrome test


followed by pressing Enter.
Am I a palindrome?
"Am I a palindrome?" is not a palindrome.


17. :
string s i . s2("Hello");
cout "Enter a line of 1nput:\n";
cin si;
If (si == s2)
cout "Equal\n";
else
cout "Not equal\n";
546 11.

:
Enter line of input:
Hello friend!

?
18. (
C++):
string si. s2("Hello"):
si = s2;
s2[0] = 'J';
cout si " " s2:


string
, C++ ,
string. ,
.
char a_c_string[] = "This is my s t r i n g . " ;
string string_variable;
string_variable = a_c_string;

A :
a_c_string = string_variable: / /

.
:
strcpy(a_c_string, string_var1able); / /

strcpy
string, C++ string
, .
, string,
. -
c_str(). string :
strcpy(a_c_string, string_variable.c_str()); //

,
strcpy. - c s t r O ,
string. ,
. ,
:
a_c_string = string_variable.c_str(): / /

string ,
. , .
11.3. 547

11.3.
, , . ,
, , .
!

,
. C++
, , ,
, , .
, ,
.


, ,
.
.
v 1 nt :
vector<1nt> v;
vector<1nt> ,
. .
, v vector<int>.

( ).
, , .
.
, - v
(1 1nt):
v[1] = 42;
cout "The answer 1s " v[1]:

: v[i ]
- , .
, .

push__back.
: ,
1, 2 . . - pushback
. ,
, 1 2 sample.
vector<double> sample;
sample.push_back(0.0);
548 11.

sample.push_back(l.l);
sampl.push_back(2.2);

.
, - size. ,
sample.sizeO 3.
sampl :
for (int 1 = 0: 1 < sample.sizeO; i++)
cout sample[i] endl;
size unsigned int, a int. (
.)
int, size
,
, unsigned int ,
i nt. ,
unsigned int int
unsigned int, for:
for (unsigned int i = 0: 1 < sample.sizeO; 1++)
cout sample[i] endl;
11.7 ,
.
11.7.
finclude <iostream>
linclude <vector>
using namespace std;

int mainO
{
vector<int> v;
cout "Enter a list of positive numbers.\n"
"Place a negative number at the end.\n";

int next;
cin next:
while (next > 0)
{
v.push_back(next);
cout next " added. ";
cout "v.SizeO = " v.sizeO endl ;
cin next;

cout "You entered:\n";


for (unsigned int i 0: 1 < v.sizeO; i++)
cout v[i] " ":
cout endl;

return 0;
11.3. 549


Enter 11st of positive numbers.
Place a negative number at the end.
2 4 6 8-1
2 added. v.slzeO = 1
4 added. v.sizeO = 2
6 added. v.slzeO = 3
8 added. v.slzeO = 4
You entered:
2 4 68
vector<1nt> ,
. ,
V :
vector<1nt> v(10);
, v.slzeO
10. v[1]
( 1
9). ,
:
for (unsigned 1nt 1 = 0; 1 < 10; 1++)
v[1] = 1:
, 9,
push_back.


, .
.
vector std. ,
, ( ) :
#1nclude <vector>
using namespace std;
_ 1<_>.
:
vector<int> v; //
// .
vector<AClass> record(20): //
//
// AClass 20 .
- pushback,
:
v.push_back(42);

,
,
.
550 11.


.
,
.
vector
std. , ,
( ) :
#1nclude <vector>
using namespace std;

:

V , 1 v.sizeO, v[1]
, v[1],
^ pushback. ,
:
v[1] = ;
,
.

:


(
, ). ,
,
.
, , ,
,
. (
12.)


, ,
.
- capac1ty(). .
,
, .
, .
,
.
11.3. 551

, , ;
( , ).
, ,
.


,
, . v
- v.sizeO v.capadtyO.

, C++
. ,
, -
. - reserve .
,
v.reserve(32);
v 32 ,
. .
v.reserve(v.s1ze() + 10);
v 10 ,
. ,
reserve , ,
, .
- resize. ,
24 :
v.res1ze(24);
24, ,
.
24, , ,
. .
reserve resize ,
.

19. :
#include <iostream>
#inclucle <vector>
using namespace std;
i n t mainO
{
vector<int> v(10):
int i ;

for ( i = 0; i < V.sizeO; i++)


v[i] = i;
552 11.

vector<int> ;
= V;
v[0] = 42:
for (i = 0; i < copy.sizeO; i++)
cout copy[i] " ":
cout endl;
return 0;
}
, ?
20. ?

, ,
. , ,
- '\'.
,
. ,
. ,
,
==. .
ANSI/ISO string
string, .
string . ,
(= ==)
string .
- ,
.



1. :
char string_var[10] = "Hello";
char string_var[10] = {''. ' e ' . ' 1 ' . ' 1 ' . ' ' . 4 0 ' } :
, .
:
char string_var[6] = "Hello":
char string_var[] = "Hello":
, .
:
char string_var[10] = {'', '', '. '. ''}:
.
553

2. "DoBeDo to you"
3. stringvar ,
( ' \'). strcat ,
,
" and Good-bye.",
stnngvar.
, , .
, ,
.
4. strlen , :
1nt strlenCconst char str[])
// : str ,
// '\0'.
// str ( '\0').
{
1nt Index = 0;
while (str[index] != '\0')
1ndex++;
return index;
}
5. ,
- '\0'.
6. ) 1;
6)1;
) 5 ( '\0');
) 2 ( '\0');
)6 ( '\0').
7. . ; ' ',
' b' ' ' ' \0'.
'', '' ''
'\0'.
8. int index = 0;
while ( our_string[index] != ' \ 0 ' )
{
our_string[index] = 'X';
index++;
}
9. a) - -
'\0', ,
, .
whi 1,
);
6)while( our_string[index] != ' \ 0 ' && index < SIZE )
554 11.

10. #1nclude <cstring>


// strcpy.

strcpy(a_string. "Hello");
11. I did 1t my way!
12. "good. I hope." astring.
, .
13. Enter some input:
The
time is now.
The-t1meEND OF OUTPUT
14. :
Enter line of input;
May the hair on your toes grow long and curly.
May t<END OF OUTPUT

15. A*string<END OF OUTPUT


16. A string is a joy forever!<END OF OUTPUT
17. :
Enter line of input:
Hello friend!
Equal

, cin ,
.
18. Hello Jello
19. . :
0 12 3 4 5 6 7 8 9
, v .

= V;

v.
20. ,
, .
, .


1. , 100

. ,
.

. : PIX
555

- .
,
.
,
. , :
the Answer to life, the Universe, and everything the
IS 42.
:
The answer to life, the universe, and everything is 42.
2. ,
, .
,
, , .
, , , .

.
,
. ,
I say H i .

:
3 words
1
1 h
2 1
1 S
1

3. , :
v o i d get_double(doubles 1nput_number);
// : input_number
// .
.
,
, 23.789, .
geti nt,
11.2, ,

doubl . ,
read_and_clean, , , 11.1,
.
.
, () .

, .
556 11.

4, , : ,
, .
:
. ,

,
Average User

:
User. .


. User


User. .


, . ,
,

User


User.

, ,
20 .
string.
, ,
. ,
getl 1 .
5. ,
"love". ,
I hate you, you dodo!

:
I love you. you love!

, . ,

John w i l l run home.

:
Love love run l o v e .

,
"Love", "love". , ,
. ,
,
557

, .
, .
6. , 10.10
10, , ,
1 nt, . ,
numberused , 10.10,

- sizeO.
, .
, 10.10.
7. 5 10,
. ( ,
.)
8. 4 10,
. , 6
7 . ,
,
.
.
12

~ ,
. ,
, ,
. ,
, .

1 2 . 1 .
.
-

. ,
( ),
. ,
, ,
. ,
, , .
, ,
, ,
, . ,
1007, : , 1007.
. ,
,
12.1. 559

. .
, .

-
. ,
, ,
1nt double. . ,

double *;

double.
double,
, 1nt
char. .

,
, . ,
:
i n t * 1 . *2. v l . v2;

1 2 int,
vl v2 int.
- .
, 2
int.
, C++ ,
.

-
_
, ,
.

_ *__1, *__2. . . . ;


double *po1nterl, *po1nter2;

,
, . ,
- 1 vl, ,
() vl, vl.
560 12.


, ,
. ! -+ ,
, .
int - ,
1 nt. ,
.
,
, , .

-, 1 2,
, , vl v2.
-
&. , :
1 = &vl;
1 vl.
:
1 ( vl, ,
1). C++ , 1,
: *1. , -
, - ,

. :
vl = 0:
1 = &vl;
1 = 42;
cout v l endl:
cout *pl endl;
:
42
42
1 vl, vl *1
. , *1 42, vl
.
&, , ,
,
. . , ^
.
& , , .
- -.

. , 1 vl,
2 = 1;
2 , vl.
12.1. 561

vl ,
cout *2:
42.
,
1 = 2:

*1 = *2;

* &
*, -, ,
.
, .
&, , ,
. .
:
double *. v;

= &V;

, v.
* , ,
* v . ,
* = 9.99;
v 99.9, v .

1 2 ,
, , (. 12.1).
,
,
.
new.
. :
1 = new 1nt:
1 nt -
1 ( 1 ).
: *1 (
, 1). ,
1 nt. , :
Gin *1:
*1 = *1 + 7:
cout *1;
1 nt, , 7
.
562 12.

. 1 2 . 1 .

new
. new. ,
new, ,
.
12.1 ,
.
1 2 . 1 .
/ / , .
#1nclude <iostream>
using namespace std;

1nt ma1n()

i n t * p l . *p2:

pi = new 1nt;
*pl = 42:
p2 = pi;
cout "*pl *pl endl;
cout "*p2 *p2 endl;
*p2 = 53;
cout "*pl *pl endl;
cout "*p2 *p2 endl;

pi = new 1nt;
*pl = 88;
cout "*pl *pl endl:
cout "*p2 *p2 endl;

cout "Hope you got the point of this example!\n"


return 0;
}

*pl == 42
*p2 == 42
12.1. 563

* p l == 53
*2 == 53
*1 88
*2 53
you got the point of this example!

Ha . 12.2 , 12.1.
,
. ,
-, .
, .
,
, . . 12.2, , 1
, .

int *1. *2:

P.Q
*2 = 53:

1 1 >1 1
1 53 1
1 = new 1nt: 1 "^i'

'Q-
.
~1 ?

1 = new 1nt; 1 1
1 1 ?
6
1 ^1 1
1 1 ^
*1 = 42

''Q-
42

*1 = 88: 1 1
rn__j ^
1 1 I J 53
2 = 1:

~]
42
2^ _J

. 12.2. 12.1.
564 12.

- =
1 2 ,
1 = 2;
1 , ,
2.

new
new
. , : .
*;
= new ;

.
,
.
, :
1nt * ;
= new 1nt(l7); // 17.
*nitPtr:
mtPtr = new (32.0. 17); / / (double. 1nt);
C++ ,
, new .


1. C++.
2. :
1nt* i n t _ p t r l . int_ptr2;
3. *.
?
4. :
1nt *1. *2;
1 = new 1nt;
2 = new int;
*1 = 10;
*2 = 20;
cout *1 " " *2 end!
1 = 2;
cout *1 " " *2 endl
*1 = 30;
cout *1 " " *2 endl
,
*1 = 30;
12.1. 565


*2 = 30;
5. :
1nt *1. *2:
1 = new 1nt;
2 = new 1nt:
*1 = 10;
*2 = 20;
cout *1 " " *2 end!;
*1 = *2; // , 4
cout *1 " " *2 endl;
*1 = 30;
cout *1 " " *2 endl;


C++ ,
( . freestore) ( .
heap). ,
, .
,
, new .
C++.
, .
,
, ; . ,
,
, delete. ,
. :
delete ;

.

.

delete
del ete
,
. , :
delete ;
, .

. (
del ete,
-.)
566 12.

:
delete -,
, , . -
, ,
, , . ,
- ,
. -
. ,
*,
. -,
, .


, new, ,
.
,
C++ .
, ,
. ,
C++ .
main,
, . (
main , ,
,
, .)
, main ,
, ,
.
, .
-
. ,
main ( 3.)
,
.

:

C++
,
. ,
typedef int* IntPtr;
IntPtr int.
12.1. 567

-
:
IntPtr ;

1nt *;

.
typedef
. ,
typedef double Kilometers:

Kilometers, , double.
double
:
Kilometers distance;


, typedef
-.
, (
IntPtr), . -,
, - .
, 1 2 ,
:
int *1. 2:

.
2 ,
i nt, .
, , ,
. C++
int .

i n t * 1. 2;

, . ,
1 2 , 1 ,
2 i nt.
i nt, ,
1. 1 2:
i n t * 1 . *2;


1 2
IntPtr:
IntPtr p i . 2;
568 12.

,
IntPtr, , -
, .
(, )
, , .
,
. :
void sample_funct1on(IntPtr& po1nter_variablG);



.
typedef. main (
, ) , .
,
.

typedef _ __:

typedef int* IntPtr:
IntPtr
int, :
IntPtr pointerl. po1nter2;


6. ,
:
char *;
= new char;
,
,
,
?
7. NumberPtr , -
int.
- my_point NumberPtr.
8. new. ;?

12.2.
, -
. , ,
12.2. 569

. ,
, .

-
10 , .
, ,
. ,
. +-
, .
:
1nt [10]:
typedef int* IntPtr;
IntPtr p:
.
, , ,
12.2. int ( [0]),
, :
= :

12.2. -
/ / , , .
#111 <iostream>
using namespace std;

typedef i n t * IntPtr;

int mainO
{
IntPtr p;
1nt a[10];
int index;
for (index = 0: index < 10: index++)
a[index] = index:
P = a:

for (index = 0; index < 10: index++)


cout pCindex] " ":
cout endl;

// ,
// .
for (index = 0: index < 10: index++)
pCindex] = p[index] + 1:

for (index = 0: index < 10: index++)


cout a[index] " ";
cout endl:

return 0:
570 12.

0 12 3 4 5 6 7 8 9
1 2 3 4 5 6 7 8 9 10

, ,
[0], [1],..., [9] [0],
[1], ..., [9]. ,
, , ,
.
.
, :
, (, ),
. , :
IntPtr 2;
// 2 .
= 2; // ( .)

, .



, ,
: ,

. ,
,
.
,
, ,
. ,
. -,
, .
-, ,
.
.
,
, .
new,
. ,

, . , :
typedef double* DoublePtr;
DoublePtr d;
d = new double[10]:
double.
12.2. 571


doubl . , doubl
.
10.


.
, . ,
double,
typedef double* DoubleArrayPtr:
-. -
.
:
DoubleArrayPtr ;
new. new:
= new double[array_s1ze]:
,
. 1nt
int. array_size int,
.
. -
. ,
: [0], [1]. . -
,
.
delete []. ,
delete -
,
. :
delete [ ] ;

. -, ,
,
,
. , double
.
- .
, -
.
, new
,
doubl . ,
.
10, doubl ,
572 12.

.
12.3, 10 1nt,
,
.
, new
.
array_size.
12.3.
/ / , ,
linclude <iostream>
#include <cstdl1b>
#1nclude <cstddef>

typedef i n t * IntArrayPtr;

void f1ll_array(1nt a [ ] . i n t size): / / .


/ / : size - .
/ / : [0] a [ s i z e - l ]
/ / , .

void sortCint [ ] . i n t size); / / .


/ / : size - .
/ / [0] a [ s i z e - l ] .
/ / : [0] a [ s i z e - l ]
/ / . [0] <= [1] <= . . . <= a [ s i z e - l ] .

int mainO
{
using namespace std;
cout "This program sorts numbers from lowest to highest.\n";

int array_size;
cout "How many numbers will be sorted? ";
cin array_size;

IntArrayPtr a;
a = new int[array_size];

fill_array(a. array_size):
sort(a. array_size);

cout "In sorted order the numbers are:\n";


for (int index = 0; index < array_size; index++)
cout a[index] " "; // a . ,
cout endl;

delete [] ;

return 0:

// iostream.
void fill_array(int [], int size)
12.2. 573

using namespace std;


cout "Enter " size " Integers.\n":
for (int index = 0; index < size; index++)
Gin a[index];

void sortCint a[]. int size)


... sort.
. ,
, ,
. , 10.10
( ). ...

delete,
12.3. ,
.
,

. del ete
del ete
:
delete [ ] :

C++, ,
.
,
1 nt. ,
delete ;

, .
ANSI C++ , , ,
, ( ,
). -
, ,
. : ,
, :
array_ptr = new [37]:

:
delete [ ] array_ptr:

new
, , 12.3.
- ,
del ete
.
, .
574 12.


9. -
, char. CharArray.
10. , ,
:
1nt *entry;
entry = new int[10];
entry,
.
, .
. ,
, 10, - entry
.
.
12. :
1nt a[10];
1nt *p = a;
int 1;
for (1 = 0: 1 < 10; 1++)
a[1] = 1 ;
for (1 = 0; 1 < 10; 1++)
cout p[1] .1 .
cout encll ;
, .
13. :
int rray_s128 = 10;
int *;
= new int[array_s1ze];
int * = ;
1nt 1;
for (1 = 0 ; 1 < array_s1ze; 1++)
a[1]=1;
p[0] = 10;
for (1 = 0 ; i < array_s1ze; 1++)
cout a[1] " ";
cout endl;
, .


( )
,
, , .
, :
typedef double* DoublePtr;
DoublePtr d;
d = new doubleClO];
12.2. 575

d d[0].
d+l d[l], d+2
d[2] . . , d ,
, d+l ,
d. double
( ) d 2001, d+l
2009. , double
, ,
.

. , array_s1ze -
, d, :
for ( i n t 1 = 0 ; 1 < array_s1ze; i++)
cout *(d + 1 ) " ";

.
:
for ( i n t 1 = 0; 1 < array_s1ze; 1++)
cout d[1] " ";

.
,
.
. , ,
, ,
, ,
. (++)
(--). , d++ d,
, d--
d .


,
.
14. :
int array_s1ze = 1 0 ;
int *:
= new int[array_s1ze];
int i:
for ( i = 0 ; i < array_size; i++)
*(a + i ) = i :

for ( i = 0; i < array_size; i++)


cout a[i] " ";
cout endl:

?
576 12.

15. :
1nt array_s1ze = 10;
1nt *;
= new 1nt[array_size];
int i;
for (1 = 0 : 1 < array_s1ze: 1++)
a[1] = 1;

while (*a < 9)


{
a++:
cout *a " ";
}
cout endl;
?


( )
C++ . ,
, . .
, , ,
,
1 nt* (
1 nt),
1 nt.

1 nt:
typedef i n t * IntArrayPtr;
,
1nt 3x4 IntArrayPtr:
IntArrayPtr *m = new IntArrayPtr[3];

1 nt,
:
for ( i n t i = 0; i < 3: i++)
m[i.] = new i n t [ 4 ] ;
m 3x4.
, 12.4.
delete.
, ,
new for, ,
deleteC],
.
. (
delete[], , ,
.)
12.2. 577

12.4,
#1nclude <1ostream>
using namespace std;

typedef int* IntArrayPtr:

int mainO
{
int dl, d2;
cout "Enter the row and column dimensions of the array:\n":
cin dl d2:
IntArrayPtr m = new IntArrayPtr[dl];
int i, j;
for (i = 0; i < dl; 1++)
mCi] = new intCd2];
// m dl d2.

cout "Enter " dl " rows of "


d2 " integers each:\n";
for (i = 0: i < dl: i++)
for (j = 0; j < d2; J+-H)
cin m[i][j];

cout "Echoing the two-dimensional array:\n";


for (i = 0 ; i < dl; i++)
{
for (j = 0: j < d2; j++)
cout m[i][j] " ";
cout endl;
}
/* , new, ,
deleted. (
, deleted ,
.) */

for ( i = 0: i < d l ; i++)


deleted m [ i ] ;
deleteC] m;

return 0;


Enter the row and column dimensions of the ^^:
3 4
Enter 3 rows of 4 integers each:
12 3 4
5 67 8
9 012
Echoing the two-dimensional array:
12 3 4
5 67 8
9 012
578 12.

12.3.

.

,
-.

. .

:
11 ,
,
, .
StringVar,
.
, .
StringVar
.
Stri ngVar - ,

. ,
. 1

- .
C++ string, ,
Stri ngVar. - ,

.
StringVar 12.5.
i nt.
,
. , ,
100 . -,
(, ). ,
.
,
, ,
. ,
, . -
-StringVar, ,
12.3. 579

. .
- StrlngVar .
12.6 ,
StnngVar. , your_name our_name,
conversation. ,
maxnamesize. our_name
"",
4 .
, StringVar
. 12.7.
StrlngVar .
new
- value. value
. ,
,
. 12.6,
1 nt.
yourname conversation.
max_name_s1ze. ,
, , ,
maxnamesize . ,
i nt.
- length, input_line
.
-StringVar .

12.5. StringVar
// strvar.h StrlngVar.
// .
// ,
// (max_size). [max_size]:
// StrlngVar the_object(max_size);
// max_size - .
#ifndef STRVAR_H
#define STRVARJ
#include <iostream>
using namespace std;
namespace strvarsavitch
{

class StringVar
{
public:
StringVar(int size);
// ,
// , size .
// . i^
580 12.

12.5 ()
StringVarO;
// ,
// 100 .
// .

StringVar(const char []):


// : .
// '\0'.
// ,
//
// strlen(a) .

StringVar(const StringVar& string_object);


// .
-StringVarO;
// .
int length const;
// .
void inputjine(istreams ins);
// : ins - .
// .
// : ins '\'
// . .
// , .

friend ostream& operator (ostream& outs, const StringVar& thestring);


// .
// StringVar.
// : outs - .
// .

private:
char *value; // ,
// .
int maxjength; //
// .
}:
} // strvarsavitch

#endif // STRVAR_H
12.6. , StringVar
// , StringVar.
#include <iostream>
#include "strvar.h"
void conversationCint max_name_size);
// .
int mainO
12.3. 581

using namespace std:


conversationOO); //
// ,
cout "End of demonstration.\n";
return 0:

// ,
void conversation(int max_name_size)
{
using namespace std;
using namespace strvarsavitch;
StringVar your_name(max_name_si2e). our_name("Borg"); //
// ,
cout "What is your name?\n":
your_name.i nputj i ne(ci n);
cout "We are " our_name endl:
cout "We will meet again " your_name endl:


What is your name?
Kathryn Janeway
We are Borg
We w i l l meet again Kathryn Janeway
End of demonstration

12.7. StringVar
// : strvar.cpp.
// ( , ..)
// StringVar.
// StringVar strvar.h.
#include <iostream>
#include <cstdlib>
#include <cstddef>
#include <cstring>
#include "strvar.h"
using namespace std;
namespace strvarsavitch
{
// cstddef cstdlib.
StringVar::StringVar(int size) : max_length(size)
{
value = new char[maxjength + 1];//+1 ' \ 0 ' .
value[0] = * \ 0 ' ;
}
// cstddef cstdlib.
StringVar:: StringVar : maxJength(lOO)
{
value = new char[max_length + 1];//+1 ' \ 0 ' .
value[0] = 'XO':
} ^
582 12.

12.7 {)
II cstring, cstddef cstdlib.
StringVar::StringVar(const char a[]) : maxjength(strlen(a))
{
value = new char[maxjength + 1]; / / +1 'XO'.
strcpyCvalue, a);
}
// cstring. cstddef cstdlib.
StringVar::StringVarCconst StringVarS string_object)
: maxj ength(stri ng_object.1engthC))
{
value new char[max_length + 1]: // +1 '\0'.
strcpyCvalue, string_object.value):
}
StringVar::~StringVar()
{
delete [] value: //
}
// cstring.
int StringVar::length() const
{
return strlen(value);

// lostream,
void StringVar::input_line(istream& ins)
{
ins.get!ine(value, maxjength + 1):
}
// iostream.
ostream& operator (ostream& outs, const StringVar& the_string)
{
outs the_string.value;
return outs;

} // strvarsavitch


. ,
delete.
- (, ,
), ,
del ete. ,
,
. ,
, ,
, , ,
del ete. -
12.3. 583

,
delete. C++
-, .
- ,
. ,
,
,
. ,
del ete ,
- .
delete.
,
.
- --StringVar Stn'ngVar,
12.5. ,
, , - ( ),
. , ,
, void. ,
, .
,
-.


- ,
. ,
,
.

. ,
. (-),
.

-Stri ngVar,
12.7, - delete ,
- value.
conversation 12.6 your_name
ourname .
StringVar , conversation
- ,
. con
versation ,
. StringVar

, ,
.
584 12.

: ,

,
. sneaky 12.8.
temp
.
, .
temp, , sneaky.
, sneaky - .
,
. sneaky * 77,
99. ?
12.8. -,
/ / , -, .
#include <iostream>
using namespace std;

typedef i n t * IntPointer:

void sneaky(IntPointer temp);

1nt mainO
{
IntPointer p;

p = new int;
*p = 77:
cout "Before call to function *p -= "
*p endl;

sneaky(p);

cout "After call to function *p == "


*p endl:

return 0;

void sneaky(IntPointer temp)


{
*temp = 99;
cout "Inside function call *temp
endl;


Before call to function *p == 77
Inside function call == 99
After call to function *p == 99
12.3. 585

, 12.8,
. 12.3. ,
, . ,
, .
sneaky , ,
, .
-
,
. ,
, .

1. sneaky 2.
temp

77 ^ \ '^'^

temp

3. Jlenue *temp 4. : snea ky

99 .. . .f^ 99
^
1
temp

. 12.3. sneaky


,
, .
, const,
.
, .
, , StringVar,
12.5, :
StringVar 11(20). motto("Constructors can help.");
cout "Enter a string of length 20 or less:\n";
I1ne.inputj1ne(cin);
StringVar tempCline); // .

,
StringVar, ,
. , 1 i
586 12.

int, motto const char [].


temp
const StringVar&. ,
.
,
.

StringVar tempdine);

- temp.value ,
- line.value;
.
, , ,
11 . val .
StringVar 12.7. :
,
. , temp
,
11 , ,
temp 11 .
, ,
. ,
. ( , C++
, .)
:
;
;
, .
,
.
, , ,
, StringVar. ,
StringVar
, , :
void show_string(StringVar the_string)
{
cout "The string i s : "
the_string endl;
}

, :
StringVar greetingC'Hello");
show_string(greeting);
cout "After c a l l : " greeting endl;
12.3. 587


. show_string,
greeting the__string,
- the_stri ng. val ue greetl ng. va -
1 ue. ,
show_str1ng
, :

greeting.value the_str1ng.value

String-
Var, thestring
. :
delete [ ] value;

thestring,

delete [ ] the_str1ng.value;

, :

greeting.value the_string.value

greeti ng. val ue thestri ng. val ue


, .

greeting.value :
cout "After call; " greeting endl;

cout . ,
, , gree
ti ng. val ue . , greeti ng
.
588 12.

,
:
delete [] greeting.value;

, , -
t1 ng. val ue, ,
. delete
( , new)
.
, StringVar
. , ,
:
StringVar greetingC'Hello");
show_string(greeting):

.
,
the_string greeting, :

"Hello" "Hello"
>^ iI

greeting.value the_string.value

, - thestring.va-
1 ue greeti ng,
. the_string,
greeting, .
,
, return.
, ,
.

new ,
. (
) .
, ,
.
,
,
.
12.3. 589



, .
, ; ,
, const.
, -
. ,
. , ,
.
, new,
.


, = ,
, ,
, . -
, , ,
. .

= , -
, 1nt double. -
, , .
, new,
, = .


16. MyClass ,
? , ?
17. ,
, 12.7:
StringVar::~Str1ngVar()
{
cout endl
"Good-bye cruel world! The short life of\n"
"this dynamic array is about to end.\n";
delete [] value;
}
12.6? ^
18.
StringVar.
StringVar::StringVar(const StringVar& string_object)
StringVar,
. .
590 12.

19. :
) , ;
) ;
) ;
) ?


, stringl str1ng2 :
StringVar s t n n g K l O ) . str1ng2(20);

StringVar 12.5 12.7. string2


, :
stringl = string2;
, , .
,
- string2 -
stringl, - stringl.maxjength
, - stri ng2. max_l ength, a
stri ngl. val ue , stri ng2. val ue.
stringl,
string2.
- stri ngl. val ue ,
string2.value.
.
stringl, string2, .
, ,
StringVar. StringVar

. ,
,
, .
,
, +.
, . StringVar
,
:
class StringVar
{
public:
void operator =(const StringVar& right_side);
// =
// .
... .
12.5. ...
12.3. 591

( )
, .
:
s t r i n g l = string2:

stringl -,
, string2 .
:
/ / ,
/ / :
void StringVar::operator =(const String\/ar& right_$ide)
{
int newjength = strlen(right_s1de.value);
i f ((newjength) > maxjength)
newjength = maxjength;
for ( i n t i = 0; i < newjength; i++)
valueCi] = r1ght_side.value[i];
valueCnewJength] = ' \ 0 ' ;
}
i f.
,
( ),
, . , ,
.

.
:
// .
void StringVar;:operator =(const StringVarS right_side)
{
delete [ ] value;
i n t newjength = strlen(r1ght_side.value);
maxjength = newjength;

value = new char[maxjength + i ] ;

for ( i n t i = 0; 1 < newjength; i++)


value[i] = right_side.value[i];
valueinewjength] = ' \ 0 ' ;
}

:
niy_string = my_string;


delete [ ] value;

mystring,
:
delete [ ] my_string.value;
592 12.

mystri ng , mystri ng. val ue


. ,
mystring, , ,
.
, ,
- ,
, , .

:
// .
void StringVar::operator =(const StringVar& right_side)
{
int newjength = strlen(right_side. value);
i f (newjength > maxjength)
{
delete [ ] value;
maxjength = newjength;
value = new char[max_length + 1];
}
for ( i n t i = 0; 1 < newjength; 1++)
value[i] = r1ght_side.value[i];
value[newjength] = ' \ 0 ' ; ^
}

,
.
.

20. ,
,
.
.

,

.
,
.

, .
,
;
del ete.
593

,
.
.
- .
,
. ,
.

, .
, , -

.
, new.
= ,
, .
, .
, new,
.



1. - .
2. ,
1 nt. ,
( intptrl, int).
1nt_ptrl int int_ptr2
1 nt.
3. int *; //
// int.
* = 17; // .
//
// 17.
4. 10 20
20 20
30 30
*1 = 30; *2 = 30;,
.
5. 10 20
20 20
30 20
6. delete ;
594 12.

7. typedef 1nt* NumberPtr;


NumberPtr my_po1nt;

8. new .

( ),
, .
, .
9. typedef char* CharArray;

10. cout "Enter 10 integers:\n":


for (int 1 = 0; 1 < 10; i++)
cin entry[i];

11. delete [] entry;

12. 0 1 2 3 4 5 6 7 8 9
13. 10 1 2 3 4 5 6 7 8 9
14. 0 1 2 3 4 5 6 7 8 9
15. 1 2 3 4 5 6 7 8 9
16. MyClass , ,
. -MyClass.
17. :
What 1s your name?
Kathryn Janeway
We are Borg
We will meet again Kathryn Janeway

Good-bye cruel world! The short l i f e of


this dynamic array is about to end.

Good-bye cruel world! The short l i f e of


this dynamic array is about to end.
End of demonstration

18. StringVar :: , ;;
- (, -
, ), StringVar
string_object.
19. ) - .
(~), ;
) ,
;
) , ;
)
. , ,
.
595

20. ,

. ,
.


1. StringVar, 12.5 12.7,
:
- _1, ;
- one_char, , -
set_char, ;
== (
, - _1 ength
);
+,
StringVar;
, (
input_line, ).
,
.
.
2. 10 10
.
int,
.
3. 9 10
.

.
4. 11 ,
, .
, -+. Vector-
Double, double.
- double.
, int: maxcount
count
. ( -
, ).
( doubl ) -
VectorDouble ,
,
, .
596 12.

:
Q : ,
50 ,
1 nt
;
;
(=);
(==).
VectorDouble ,
- count count ;
- maxcount ;
- push_back, capacity, size, reserve resize,
, - ;
-, ,
: value_at(i), i-ro
, change_value_at(d. i), i- ^
d doubl .
. (
; ,
.)
Text, .
StringVar,
StringVar, char,
StringVar StringVar, ,
' \0'. Text ,
. StringVar
( ,
).
Text -,
- StringVar. const char []
Text , i nputl i ne.
('\'),

.
- i nput_l i ne , ,

StringVar.
. Text
StringVar . ,
, .
Text , 1.

.
597

6. ,
, .
. .

. :
** + X + 1


doubl ,
.
* ?
, ,
.

(
).
.
,
, ,
. ,
= .
:
+ ;
+ ;
+ ;
- ;
- ;
- ;
* ;
* ;
* .
,
,
double.
, : ,
.
13


.
, ,
, ,
, .
, .
? .
.

,

.
, , , ?
, , , ,
, ~ .
: , .
? .
:
, , ,
!
.

.
C++.
, whil ,
. while,
.
://?//. C++ .
, . -
]^ .
C++,
.
13.1. , 599

13.1. ,

,

, ,
, .

- ,
. ,
.
, ,
: .

. ,

, , C++. .

:
void,
, ,
1984 :
1
9
8
4


:
void wr1te_vertical(1nt );
// : >== 0.
// : .
// - .


.
, .
, , :
: < 10. .
, ,
. , 1234, :
1
2
3
4
600 13.

.
1. :
1
2
3
2. , 4.
1 ,
. 2
. wr1 -
te_vert1cal :
if ( < 10)
{
cout endl:
}
else // n 2 .
{ // .
write_vert1cal( );
cout endl;
}
,
C++ :



:
/10 // .
%10 I I .
, 1234/10 123, 1234^10 ~ 4.

, .
, wri -
te^vertical, , .

/10.
,
1 .
2. .
,
. ,
.
,
.
13.1. , 601

, ( ,
),
, .


( 13.1).
.

, :
wr1te_vertical(l23);

1 3 . 1 .
/ / , wr1te_vertical.
#1nclude <iostream>
using namespace std:

void write_vertical(int n);


// : n >= 0.
// : n .
// - .

int mainO
{
cout "write_vertical(3):" endl;
write_vertical(3);

cout "write_vertical(12):" endl;


write_vertical(12):

cout "write_vertical(123):" endl;


write_vertical(123);

return 0;

// iostream.
void write_vertical(int n)
{
if (n < 10)
{
cout n endl;
}
else // n 2 :
{
writevertical(n/10);
cout (n^lO) endl;
602 13.


wr1te_vertical(3):
3
write_vert1cal(l2):
1
2
write_vert1cal(l23):
1
2
3

write_vertical, ,
. 123
, .
:

7 f (123 < 10)


{
cout 123 endl:
}
Ise II n 2 :
{
wr1te_vert1cal(123/10): ,
cout (123^10) endl

}

123 10, if...else


f al se el se.
:
wr1te_vertical(n/lO):
( 123) :
wr1te_vertical(123/10);
, , :
wr1te_vert1cal(l2):
,
.
.

write_vert1cal(l2);
, . 12
, .

npi , .
13.1. , 603

1f (123 < 10)


{
/f (12 < 10)
cout
} cout 12 endl;
else li
{ e/se // n 2 :
wr1t
cout {
write vert1caUl2/lO): ^.
}
cout (12X10) endl: "
1

12 10, i f ...el se
f al se el se. , ,
. , /10,
12/10. , ) write_vertical
:
write_vertical(12/10);
:
write_vertical(l);

, ,
, . 1 ,
.
.

if (123 < 10)


{
if (12 < 10)
{
} if (1 < 10) ^ ^ ^
/
^^^ ,
} { ^ ^
? cout 1 endl: ^ ^""^

{ } - ^
else II n 2 :
{ {
}
wr1te_vert1cal(l/lO);
cout (10) endl;
}
}

. 1 10,
if...else true
1 f. cout, 1,
wr1te_vert1cal(l)
.
604 13.

writever-
t1ca1 , ,
.

1f (123 < 10)


{
if (12 < 10)
cout
} {
cout 12 end!;
else I.
{ }
else II n 2 :
wr1t^
cout {
wr1te_vert1cal(12/10):
} '
cout (12^10) endlT

cout,
12^10, 2.
,
.

if (123 < 10)


{
cout 123 endl:
}
else II n 2 :
{

wnte_vert1cal (123/10)
cout (123^10) endl

( ) ,
123^10, 3,
wr1te_vert1cdl .
1, 2 3, .


write_vertical . ,
, wr1te_vert1cal (123), .
, ,
. 123 ,
.
write vert1cal(l23/lO):
; .
13.1. , 605

.
.
,
,
. ,
, .
,
.
C++
.
,
.
.

,
.

.
.
,
, if...else.
, .
, , ,
.
, -
.
-
. (

.)

,

.
wr1te_vertica1, 13.1.
,
, 10, ,
,
.

:
writevertlcal
,
, (
606 13.

).
, , ,
. .
, ,
. ,
,
, ( -
; ).
.
+-,
wri te_verticdl.
void new_write_vert1cal(1nt n)
{
new_wr1te_vert1cal (n/10);
cout (n^lO) endl;
}
, wr1te_ver-
tical, ,
. , . ,
new_wr1te__vertical
, , .

. , 12,
new_write_vert1cal (12/10),
new_write_vertica1 (1).

new_wr1te_vert1cal(1/10);

new_wr1te_vertical (0):
? new_wr1te_vert1cal (0/10), :
nGw_wr1te_vertical (0);
new_write_vertical (0/10), . . .
new_wr1te_vert1cal ,
( ,
).

1. :
#1nclude <1ostream>
using namespace std;
void cheers(int n);
i n t mainO
{
cheers(3);
13.1. , 607

return 0;
}

void cheers(int n)
{
if (n == 1)
{
cout "HurrayXn";
}
else
{
cout "Hip ";
cheers(n-l);
}
}
2. void ,
,
(' *') .
3. voi d ,
,
. , 1234,

4321

4. void,
int 1, 2, 3, ... .
5. void,
int , -1,... 3, 2, 1.
. , 4
5 ( ) .


,
,
. . ,
.
,
.
.
.
, ,
. :
. , ,
, .
,
(Last In First Out LIFO).
608 13.

.
,
.
. ,
, ,
, .
, ,
. ,
.

. ,
, . , ,
, .
.
, ,
.
,
.
, , ;
. , ;
, . .
. ,
, ; ,
, .
, ,
, . ,
,
.
,
.
, ,
.
. (
) ,
.
,
.
, .


,
.
, .
.
13.1. , 609

:
.
,
,
, .
, , , ,
.
.



. , ,
. ,
13.2 ,
13.1. ,
, ,
. wr1te_vert1cal, 13.1,
13.2, .

.
,
. wri -
tevertical 13.2 ,
, 13.1,
^ .
,
, ,
. ,
,
.
, ,
,
.
13.2. , 13.1
/ / iostream.
void wr1te_vert1cal(1nt )
{
1nt tens_in_n = 1;
int 1eft_end_p1ece = n;
while (1eft_end_p1ece > 9)
{
left_end_p1ece = left_end_piece/10;
tens_1n_n = tens_1n_n*lO;
} ^
610 13.

13.2 {)
II tens_in_n - 10
// , . , 2345.
// tens_1n_n 10 000.

for (int power_of_10 = tens_1n_n;


power_of_10 > 0: power_of_10 = power_of_10/10)
{
cout (n/power_of_10) endl:
n = n^power_of_10;


6. ,
?
7. cheers, 1.
8. , 2.
9. , 3.
10. 4.
. 5.

13.2. ,

,

, , void,
.
.
,
, void.
,
.

. void,

.

.
( , void).
.
13.2. , 611

:
3 pow,
. , pow(2.0, 3.0) 2.0^ ,
double X = pow(2.0. 3.0);
8.0.
pow double
. 13.3 ,
1nt. power. ,
i n t = power(2. 3):
8.
power ,
pow. pow
double, .
,
, power.
power :

13.3. power
// , power.
#1nclude <1ostream>
#1nclude <cstdl1b>
using namespace std;

int power(int x. int n);


// : n >= 0.
// x .

int mainO
{
for (int n = 0; n < 4; n++)
cout "3 to the power " n
" is " powerO, n) endl;
return 0;
}
// iostream cstdlib.
int power(int x, int n)
{
if (n < 0)
{
cout "Illegal argument to power.\n";
exit(l);
}
if (n > 0)
return ( powerCx, n - l)*x );
else // n == 0
return (1);
612 13.


3 to the power is 1
3 to the power 1 is 3
3 to the power 2 is 9
3 to the power 3 1s 27

C++ , ,
power(. ), ,
powerCx. -1)*
power, 13.3,
, > 0.
. , power(. ) 1 ( 1).
, , power
. :
power(2. 0)

,
2, , .
, if...else.
, return,
el se, 1. , :
i n t = power(2, 0):

1.
, :
power(2. 1)
2, -
1, .
, return:
return (power(x, n-l)*x );


return ( power(2. 0)*2 );
power(2, 1) ,
,
, power(2. 0).
, power(2. 0) 1. ,
power(2. 0) 1,
power.
power(2. 1), return
power(2. 0)*2


1*2
2.
13.2. , 613

, , power (2. 1),


2. :
1nt Z = power(2. 1);

z 2.

.
cout power(2. 3);

power(2. 3) :
power(2. 3) power(2. 2)*2
power(2. 2) power(2. 1)*2
power(2. 1) power(2. 0)*2
power(2. 0) 1 ( )
, power (2.0),
. ,
, ,
,
power(2, 1).
,
, power(2. 3). . 13.1.

1*2 } 10 2

2*2 4

4*2 8

power(2. 3)^
power(2. ^il 8

. 1 3 . 1 . power(2, 3)
614 13.


12. :
#inclucle <1ostream>
using namespace std;
int mystery(int n);
// : n >= 1.

int mainO
{
cout mystery(3);
return 0;

int mystery(int n)
{
if (n <= 1)
return 1;
else
return ( mystery(n - 1) + n );
}
13. :
#inclucle <iostream>
using namespace std;
int rose(int n);
// : n >= 0.

int mainO
{
cout rose(4);
return 0;

int roseCint n)
{
if (n <= 0)
return 1;
else
return ( rose(n - 1) * n );
}
rose?
14. power,
. :
double.
:
double power(int . int n);
// : < 0. 0.
//

, :" = 1/(:").
13.3. 615

13.3.
: , ,
, .



.
,
.
power, 13.3. :
power(x. ) power(. -1)*
od^~^*x,
,
.
,

.
,
. ,
,
1. . (
,
.)
2. .
3. ,
, , .
power 13.3.
1. . power(x.n)
1,
power(, 0),
. .
2. .
power(. 0), 1,
of 1.
.
3. ,
, , .
, , > 1. , power (.)

powerCx. -1)*
616 13.

,
: powerCx, -1) , powerCx. -1)
""\ power(x.n) ""^*, ^",
powe (, ).
, ,
power. (
, , .)
,
.
void. ,
,
.

:

,
. ,
, .
, , .
10 (. 10.10)
.
.
f 1 11 ndex.
, . ,
:
[0] <= [1] <= [2] <= ... <= [finalJndex]
,
, , .
,
.
,
.
, , .


, . , found, bool.
, true.
, location,
. key,
:
: [0] a[f1nal_index]
.
13.3. 617

: key
[0] a[final_1ndex].
found == false:

a[location] =- key found == true.


.
. ,
, .

, . ,
, , .
? ,
. ,
, .
, :
found = false:
mid = finaljndex:
if (key == a[mid])
{
found = true;
location = mid;
}
else i f (key < a[mid])
[0] a[mid-l];
else i f (key > a[mid])
a[mid+l] a[final_index];

, ,
, .
.
-+-+.
. :
search [0] through a[mid-l];

search a[mid+l] through a[final_index];


.
, .
mid-1,
mi d+1 f i nal_i ndex.
,
f i rst 1 ast.
final index, :
found = false;
mid = first last;
if (key == a[mid])
{
618 13.

found = true;
location = mid;
}
else if (key < a[m1d])
a[f1rst] a[m1d-l]:
else if (key > a[m1d])
a[m1d+l] a[last];

first finaljndex last.
first last. ,
first , last mid-l.
, ,
.
,
, , ,
. f 1 rst,
1 ast. ,
fi rst last, , key
. ,
, 13.4.
13.4.
int a[Some_Size_Value]:

a[first] a[last].

// :
// a[first] <= a[first+l] <= a[first+2] <= ... <= a[last]
key:

i f (first > last) // .


found = false:
else
{
mid = first last:
if (key == aCmid]) // .
{
found = true:
location = mid:
}
else i f key < a[mid] // , :
a[first] a[mid-l].
else i f key > a[mid] // , :
a[mid+l] a[last].
}

C++. -
13.5. search
13.4.
. 13.2.
13.3. 619

, search , ,
.
.

first last. -
,
. ,
first last finaljndex .
.
13.5.
/ / , .
#include <1ostream>
using namespace std;
const i n t ARRAYJIZE = 10;

void searchCconst int a [ ] . int f i r s t , int last,


int key, bool& found, int& location);
/ / : aCfirst] a[last] .
/ / : key
/ / [0] [finalJndex], found == false;
/ / a[location] == key found == true.

i n t mainO
{
i n t a[ARRAY_SIZE];
const Int f i n a l j n d e x = ARRAY_SIZE - 1:

. . . .
. . ...

i n t key. location;
bool found;
cout "Enter number to be located: ";
cin key;
searchCa, 0, finaljndex, key, found, location);

i f (found)
cout key " is in index location "
location endl;
else
cout key " is not in the array." endl;

return 0;

void searchCconst int a[]. int first, int last.


int key. bool& found. int& location)
{
int mid;
if (first > last)
{
found = false;
} ^
620 13.

13.5 ()
else
{
mid = ( f i r s t + l a s t ) / 2 :

i f (key == a[mid])

found = true:
location = mid:

else i f (key < a[mid])

search(a. f i r s t , mid-1, key. found, location):

else i f (key > a[mid])

search(a. mid+1. last. key. found, location):

key 63

a[0] 15 -M f i r s t == 0 a[0] 15
a[l] 20 a[l] 20
a[2] 35 a[2] 35 < He
a[3] 41 a[3] 41
a[4] 57 rm'rl /Tl + Q W ? a[4] 57
IIIIU K\j ^ J / c.

a[5] 63 a[5] 63 -< first == 5


a[6] 75 _ ^ a[6] 75
a[7] 80 a[7] 80 rm'H - 1 n V
^ III 1 U V.O ^ J ^ / ^

a[8] 85 aC8] 85
a[9] 90 -< l a s t == 9 a[9] 90 -< last 9

a[0] 15
^
a[l] 1o
a[2] 35
a[3] 41
a[4] 57 mid = (5 + 6) / 2 mo 5
a[mid] paeno a[5] == 63
a[5] 63 first == 5
found = t r u e :
a[6] 75 -< last == 6 location = mid:
a[7] 80 X
a[8] 85 \ He
a[9] 90

. 13.2. search
13.3. 621



,
void. search, 13.5.
1. .
first last.
,
first > last,
.
2. .
: first > last key == a[ni1d].
.
first > last, a[first] a[last]
, key
. (, !) , first > last,
search found false.
key == [mid], search found
true, location mid. ,
.
3. , :
, .
: key < [mid],
key > [mid]. .
, key < [mid]. ,
, , key
a[first] a[mid-l].
,
search(a. first. m1d-l. key. found, location;
A , .
, key > [mid]. ,
, , key
a[mid+l] [last].
,
searchCa. mid + 1. l a s t . key. found, location);
A ) , .
, (,
, ).
search , ,
.


.
622 13.

, ,
. . , .
100
7 ,
50 . , ,
. 1000
10 ,
500
.
search 13.6.
.
. f 1 rst 1 ast
.
, ,
,
.
. 13.6.

void search(const i n t a [ ] . int low_end. i n t h1gh_end.
i n t key. bool& found. 1nt& location):
/ / : a[low_end] a[high_end] .
/ / : key
/ / [0] a[high_end]. found -= false:
/ / a[location] == key found == true.


void search(const i n t a [ ] , i n t low_end. i n t high_end.
i n t key. bool& found. int& location)
{
i n t f i r s t = lowend;
i n t last = highland;
i n t mid:

found = false:
while ( ( f i r s t <= last) && !(found))
{
mid = ( f i r s t + l a s t ) / 2 :
i f (key == a[mid])

found = true:
location = mid:

else i f (key < a[mid])

last == mid - 1;

else i f (key > aCmid])

f i r s t = mid + 1;
13.3. 623

: -
- . -
, . 13.7
. BankAccount
BankAccount, 6.5, ,
- update.

. () 1 nt,
. ,
. update .
years, :
years 1. // :
update ( ).
years 1. // :

years-1 update
( ) .

, ,
, .
1. .
, years, , 1,
.
2. .
years == 1.
,
- update, 6.
3. , :
, .
, , years > 1, .
years-1 ,
,
- update .
, ,
, years > 1, .

13.7. -

// , - update(years).

#include <1ostream>
using namespace std;

// BankAccount
// , 6.6. ^
624 13.

13.7 {)

II :
class BankAccount
{
publi :
BankAccount(int dollars, int cents, double rate);
// Sdollars.cents
// rate .
BankAccount(int dollars, double rate):
// Sdollars.OO
// rate .

BankAccountO;
// $0.00
// 0.0^.

// .

void updateO;
// :
// .
void update(int years);
// :
// .
// .

double get_balance();
// .

double get_rate():
// .

void output(ostream& outs);


// : outs - .
// .
// :
// outs,
private:
double balance;
double interest_rate;
double fraction(double percent);
// .

int mainO

BankAccount your_account(100. 5 ) ;
your_account.update(10);
cout.setf(ios::fixed);
cout.setf(ios::showpoint);
cout.precision(2);
cout "If you deposit $100.00 at 5^ interest. thenXn"
13.3. 625

"in ten years your account w i l l be worth $"


your_account.get_balance() endl;
return 0;
}

void BankAccount::update
{
balance = balance + fraction(interest_rate)*balance;
}

void BankAccount::update(int years)


{
if (years == 1)
{
updateO; // .
}
else if (years > 1)
{
updateCyears - 1); // .
updateO: // .

... - 6.4 6.5.


. . . .


If you deposit $100.00 at 5^ interest, then
in ten years your account will be worth $162.89

-
update. , .
.
. up
date update
. update
. , )^, up
date - , post_
one_year(), update :
void BankAccount::update(int years)
{
if (years == 1)
{
post_one_year();
}
else if (years > 1)
{
update(years - 1);
post_one_year();
626 13.


.
.
, . ,
,
. -+ , ,
, , .

, . ,

, .


15. :
1nt squares(int n);
// : n >= 1
// 1 .
, squares(3) 14, 1^ + 2^ + 3^ 14.
16. - BankAccount: :update(1nt years)
, 13.7.

,
.

:

.

.
,
,
.
-
. ,
,
. ,
,
(, ,
).
627



1. 1 1 Hurray
2. void s t a r s d n t )
{
cout '*';
i f ( > 1)
815( - 1);
}
:
void s t a r s d n t )
{
i f ( <= 1)
{
cout ' * ' ;
}
else
{
starsCn - 1);
cout '*';

3. void backwarddnt )
{
1f (n < 10)
{
cout ;
}
else
cout (^); // .
backwad(/10): // .
}

4. #1nclude <1ostream>
81 8 std;
void write__up(int )
{
if ( >= 1)
{
write_up( - 1);
cout " "

it mai()
{
cout "callig write_up(" 10 ")\"
write_up(10);
cout edl;
return 0:
628 13.

wnteupdO):
1 2 3 4 5 6 7 8 9 10

5. #1nclude <1ostreafTi>
using namespace std:
void wr1te_down(int n)
{
if (n >= 1)
{
cout n " ":
wr1te_down(n - 1);
}
}
int mainO
{
cout "calling write_down(" 10 ")\n":
write_down(10);
cout endl;
return 0;
}
writedowndO):
10 9 8 7 6 5 4 3 2 1

6. ,
, .
.
7. void cheers(int n)
{
while (n > 1)
{
cout "Hip ";
n;
}
cout "HurrayVn":
}
8. void starsCint n)
{
for (int count = 1: count <= n; count++)
cout '*';
}
9. void backward(int n)
{
while (n >= 10)
{
cout (n^lO); // ,
n = n/lO; // .
}
cout n;
629

10. 4: = 3, :
i f (3 >= 1)
{
wr1te_up(3 - 1);
cout 3 " ";
}
= 2, :
i f (2 >= 1)
{
wr1te_up(2 - 1);
cout 2 " ":
}
= 1, :
if (1 >= 1)
{
write_up(l - 1):
cout 1 " ";
}
, = , :
if ( >= 1) // false, .
{
// .
}
-, , ,
. : 1 2 3.
11. 5: = 3, :
i f (3 >= 1)
{
cout 3 " ";
wr1te_down(3 - 1);
}
= 2, :
i f (2 >= 1)
{
cout 2 " ";
wr1te_clown(2 - 1)
}
= 1, :
if (1 >= 1)
{
cout 1 " ";
write_ciown(l - 1)
}
, = , ,
1 f, :
if ( >= 1 ) // false.
{
// .
630 13.

12. 6
13. 24. ,
] :
\ ='*(- 1)*(-2)*...*1
14. // iostream cstdlib.
double powerdnt , 1nt n)
{
i f (n < && X == 0)
{
cout "Illegal argument to power.\n";
exitd);
}
if (n < 0)
return (l/power(x. -n));
else if (n > 0)
return (power(x. n - l)*x):
else // n == 0
return (1.0);

15. 1nt squaresdnt n)

if (n <= 1)
return 1;
else
return (squaresCn - 1) + n*n);

16. void BankAccount: .-updatednt years)

for d n t count = 1; count <= years: count++)


updated;


1. int,
- .
8 7.
.
2. index_of_smallest,
10.10 10.
.
3.
, , :
(, ) = \/(\*( - )!)
, , \, :
\ =^*(- 1)*(- 2)*...*1
631

,
.
.
4. ,
,
.
. , :
[1] == '' [2] == '' [3] == ' [4] == 'D' [5] == ''
2 5, ,
:
[1] == "" [2] == '' [3] == 'D' [4] == ' [5] == ''

.
, ,
(, )
.
,
. .
5.
4. .
6.
. :
,
.
, 10.
. 10
indexofsmallest -
.
7. . ,
- 64 . ,

, .
, ,
.
.
,
.
, .
,
. ,
. ,
.
632 13.

. - -1
,
.
( ), -1
,
. . ,
, ,
.
14

.
.
, .
X Y.
Z X.
, Z Y.
.
.
, .

C++.
,
. ,
, ,
.

14.1.


,
. swapvalues,
4. :
void swap_values(int& varlablel. 1nt& var1able2)
{
int temp;
temp = varlablel;
varlablel = var1able2;
var1able2 = temp;
634 14.

1 nt, ,
,
char. ,
char,
void swap_values(char& variablel, char& var1able2)
{
char temp;
temp = variablel;
varlablel = van'able2;
var1able2 = temp:
}
swapvalues
, .
,
1 nt, char.
double
, ,
.
.
C++,
:
void swap_values(rH/7_nepeA/ewwoH& variablel.
THn_nepeMeHHO(i&i variable2)
{
_ temp:
temp = variablel;
variablel = variable2;
variable2 = temp;
}
. ,
. C++ ,
,
.


14.1 C++ swap_values,
,
. :
tempiate<class >
.
, , . (
class ^.) ,
ANSI , class
typename. , ,
class ,
.
14.1. 635

, C++.
, .

. , swapvalues
.
double:
void swap_values(doub1e& varlablel. doub1e& var1able2)
{
double temp;
temp = varlablel;
varlablel = var1able2;
var1able2 = temp;
}

,
int char. , 14,1,
swapval ues ,
.
14.1.
// , .
#1nclude <1ostream>
using namespace std;

// varlablel var1able2.
tempiate<c1ass T>
void swap_values(T& varlablel. T& variable2)
{
T temp;
temp = varlablel;
varlablel = variable2;
var1able2 = temp;
}
int mainO
{
int integer1 = 1. integer2 = 2;
cout "Original integer values are "
integerl " " integer2 endl;
swap^valuesCintegerl. integer2):
cout "Swapped integer values are "
integerl " " integer2 endl;
char symboU = 'A'. symbol2 = 'B';
cout "Original character values are "
symbol 1 " " symbol2 endl;
swap__values(syniboll, symbol2):
cout "Swapped character values are "
symbol 1 " " symbol2 endl;

return 0;
636 14.

Original integer values are 1 2


Swapped integer values are 2 1
Original character values are A
Swapped character values are A

Ha swapvalues
, ,
;. ,
, .

, . ,
swapvalues 14.1 :
int char.
14.1:
swap_values(i ntegerl. i nteger2):

C++ ,
( i nt) ,
i nt. ,

swap_values(symbol 1. symbol2);

( char)
, char.
, , ,
, .
.
, 14.1
; main ,
. ,
, -
. ,
,
.
, ,
. ,
,
, ,
( , ).
, #include,
.
, ,
.
.
14.1. 637

,
, ,
.

. ,
C++.
, ; C++,
. ,
swapvalues, 14.1, ];-
:
tempiate<class Vari>
void swap_values(VariableType& varlablel.
VariableType& van'able2)
{
VariableType temp;
temp = varlablel;
varlablel = variable2;
var1able2 = temp;
}
. ,
, 1 2, :
tempiate<class Tl. class T2>

. ,
,
, tempi ate,
.

:
,
,
. .
,
, ,
.
, ,
; #include. ,
- , ,
, #include .
C++
. ,
. ,

.
638 14.


:
tempiate<class _>
( )

.
, :
tempiate<class >
void show_stuff(int s t u f f l . T stuff2. T s t u f f 3 ) :
:
tempiate<c1ass >
void show_stuff(1nt stuffl. T stuff2. T stuff3)
{
cout stuffl end!
stuff2 endl
stuffs endl;
}

.
.
:
show_stuff(2. 3.3. 4.4);
,
doubl . ,
, ,
, .


swap_values
, ,
. C++
. .
, ,
,
.
, C++ .


1. maximum.
( , ).
, .
<, ,
.
, .
14.1. 639

2.
: abs, labs fabs, .

. ,
absolute. ,
<, -,
0. , absolute
, int, long double.
, .
3. C++.
4. , :
template <class >
) ;
) ;
) C++;
) , C++
.

:
10 int.
C++ sort,
10.12. :
void sortCint []. 1nt number_used)
{
int index_of_next_smallest;
for (int index - 0; index < number_used-l; index++)
{ // a[index] :
index_of_next_srnallest =
index_of_smallest(a. index. number_used);
swap_values(a[index]. a[index_of_next_smallest]);
// a[0] <= a[l] <=...<= a[index] -
// .
// .

, ,
- .
double,
double. ,
, .
, sort. : swap_
values index_of_smallest.
, ,
(. 14.1).
640 14.

1ndex_of_smallest ?
10:
int 1ndex_of_smal lest (const i n t a [ ] , 1nt s t a r t j n d e x . 1nt number_used)
{
i n t min = a [ s t a r t j n d e x ] ;
int 1ndex_of_m1n = s t a r t j n d e x ;
for ( i n t index = startJndex+1;
index < number_used; index+-<-)
i f (a[index] < min)
{
min = a[index];
index_of_min = index;
// min -
// aCstart index] a[index].

return index_of_min;
}

.
int double,
1ndex_of_smallest, double.
, sort
double,
1 nt doubl . ,
. , ,
<.
, , .
sort index_of_smallest
Int , sort
, <. ,
, 14.2.
14.2.
/ / sortfunc.cpp

tempiate<class >
void swap_values(T& varlablel. T& var1able2)
. . . swap_values 14.1. ...

tempiate<class BaseType>
i n t index_of_smal lest (const BaseType a [ ] . i n t s t a r t j n d e x , i n t number_used)
{
BaseType min = a[start_index];
i n t index_of_min = s t a r t j n d e x ;

for ( i n t index = s t a r t j n d e x + l ; index < number_used; index++)


i f (a[index] < min)
{
min = a[index];
index_of min = index;
14.1. 641

/ / m1n - a [ s t a r t j n d e x ] [11]
}
return index of min;

tempiate<class BaseType>
void sort(BaseType a [ ] . 1nt number_used)
{
int 1ndex_of_next_smallest;
fordnt index = 0; index < number_used-l; index++)
{ // a[index] :
1ndex_of_next_sma11 est =
1ndex_of_smanest(a. index. number_used);
swap_values(a[index], a[1ndex_of_next_smallest]);
// a[0] <= a[l] <=...<= a[index] -
// .
// .
}
}
, sort, 14.2,
, .
14.3
. <,

, ,
. , ,
, , .
.
, .
, 14.3, .

sort. (
,
<.)
14.3.
/ / .
#1nclude <1ostream>
using namespace std;

/ / sortfunc.cpp :

/ / tempiate<class BaseType>
/ / void sortCBaseType a [ ] . i n t number_used);

// .
// . ,
// sortfunc.cpp. include.
// main.

'
642 14.

14.3 {)
II : number_used .
// [0] a[number_used-l] .
// : [0] a[number_used-l]
// , [0] <= [1] <= ... <= a[number_used-l].

#include "sortfunc.cpp"

1nt mainO
{
1 nt 1:
int a[10] = {9. 8. 7. 6. 5. 1. 2. 3. 0. 4};
cout "Unsorted integers:\n";
for (1 = 0; 1 < 10; 1++)
cout a[1] " ";
cout endl;
sortCa, 10);
cout "In sorted order the integers are:\n";
for (i = 0 : i < 10; i++)
cout a[i] " ";
cout endl;
double b[5] = {5.5. 4.4. 1.1. 3.3. 2.2};
cout "Unsorted doubles:\n";
for (i = 0; i < 5; i++)
cout b[i] " ";
cout endl;
sort(b. 5);
cout "In sorted order the doubles are:\n";
for (i = 0 ; i < 5; i++)
cout b[i] " ";
cout endl;

char c[7] = {'G'. 'E'. 'N'. 'E'. 'R'. ' . 'C'};


cout "Unsorted characters:\n";
for (i = 0; i < 7; i++)
cout c[i] " ";
cout endl;
sortCc. 7):
cout "In sorted order the characters are:\n";
for (i = 0 ; i < 7; i++)
cout c[i] " ";
cout endl;

return 0;
}

Unsorted integers:
9 8765 12 3 0 4
In sorted order the integers are:
0 12 34 5678 9
Unsorted doubles:
5.5 4.4 1.1 3.3 2.2
In sorted order the doubles are:
1.1 2.2 3.3 4.4 5.5
14.1. 643

Unsorted characters:
GENERIC
In sorted order the characters are:
EEG IN R

:
, 14.2,
, int.
, .
. ,
- ,
, ,
. .
-, ,
, . -,
; ,
, .

:

,
, . ,
.
, swap_values (. 14.1)
, ,
. ,
:
int [10]. [10];
... , . ...
swap_values(a. b ) ;

,
.

5. 10.10 10 search,
int.
, .
, . .
10.10.
6. 9 3
abs ,
.
, 2.
644 14.

14.2.
...
,

,
. ,
.


, .

tempiate<class >
,
. , .
,
.
:
// .
tempiate<class >
class Pair
{
public:
PairO:
Pair(T f1rst_value. T seconcl_value):

void set_element(int position, T value):


// : position 1 2.
// : ,
// position, value.

get_element(int position) const:


// : position 1 2.
// ,
// position,
private:
first: // .
second: // .
}:
; i nt,
, - char, , . .
.
, . ,
14.2. 645

score
seats :
Pa1r<int> score;
Pa1r<char> seats;
. ,
score,
, 3 :
score.set_element(l. 3);
score.set_element(2. 0);
- , -
. ,
. - set_element
:
// iostream cstdlib:
temp]ate<class >
void Pair<T>;:set_element(int position. T value)
{
i f (position == 1)
f i r s t = value;
else i f (position == 2)
second = value;
else
{
cout "Error: Illegal pair position.\n";
exit(l);
}
}
tempiate<class T>
Pair<T>::Pair(T first_value. T second_value)
: first(first_value). second(second_value)
{
// .
}
,
Pai <>, Pai .
.
, ,
, :
int add_up(const Pair<int>& the_pair);
// , the_pair.
, ,
.
. ,
add_up
, :
tempiate<class >
add_up(const Pair<T>& the_pair);
646 14.

// : +.
// , the_pa1r.


-
:
tempiate<class _>
, , ,
.
:
tempiate<class >
class Pair
{
public:
PairO;
Pair(T f1rst_value. T seconcl_value):
void set_element(1nt position. T value):

- .
, -
:
tempiate<c1ass >
void Pair<T>::set_element(int position. T value)


, ,
:
Pair<int>
, Pair<int>,
. ,
.
,
, Pair<int>.
:
typedef _<_> __:
:
typedef Pair<int> PairOflnt:
PairOflnt
Pair<int>, :
PairOflnt pairl. pair2:
, .
14.2. 647

: 1-
14.4 ,
.
, . ,
, 1nt, double, string . .
, ,
14.5. ,
, .
14.6.
, ,
List.
.
, , L1st<ItemType>. ,
int,
L1st<int>.
14.4. List
/ / l i s t . h . L i s t .
/ / List .
/ / =.
/ / .
/ / Type_Name :
// List<Type_Name> the_object(max):
#1fndef LIST_H
#define LIST_H
#1nclude <1ostream>
using namespace std:

namespace l i s t s a v i t c h
{
temp]ate<class ItemType>
class List
{
public:
Listdnt max):
// ,
// max ItemType.
-ListO:
//
// .
int lengthO const:
// .
void adddtemType newjtem):
// : .
// : newjtem.
bool full const:
// true, . ^
648 14.

14.4 ()
void eraseO:
// , .

friend ostream& operator (ostream& outs.


const List<ItemType>& thejist);
// .
// .
// .
// : outs ~ .
// ,
private:
ItemType *item; // .
// ,
int maxjength: //
// ,
int currentjength: // .
}:
} // listsavitch
#endif //LIST_H

14.5. , List
// , List.
#include <iostream>
#include "list.h"
#include "list.cpp" // list.cpp
// ( main),
using namespace std;
using namespace listsavitch;

int mainO
{
List<int> f 1 r s t j i s t ( 2 ) :
firstjist.add(l);
firstjist.add(2);
cout " f i r s t j i s t = \n"
firstjist:
List<char> secondJist(lO);
secondJist.add('A');
secondJist.add('B');
secondJist.add('C');
cout "secondjist - \n"
secondjist:

return 0:

firstjist =
1
2
secondJ i st
A
14.2. 649

14.6. List
// : list.cpp.
// List.
// list.h.
#ifndef LIST_CPP
#define LIST__CPP
#include <iostream>
#include <cstdlib>
#include "list.h" // .
// #ifndef list.h
// ,
// .
using namespace std;

namespace listsavitch
{
// cstdlib:
tempiate<class ItemType>
List<ItemType>::List(int max) : maxjength(max). currentJength(O)

item = new ItemType[max];


}

tempiate<class ItemType>
List<ItemType>: .ListO
{
delete [] item:

tempiate<class ItemType>
int List<ItemType>;:length() const
{
return (currentjength):
}

// iostream cstdlib:
tempiate<class ItemType>
void List<ItefflType>::add(ItemType newjtem)
{
i f (fullO)
{
cout "Error: adding to a full list.Xn";
exit(l):
}
else
{
itemCcurrentJength] = newjtem;
currentjength = currentjength + 1;

tempiate<class ItemType>
bool List<ItemType>::fun() const J^
650 14.

14.6 ()
{
return (currentjength == maxjength);
}
tempiate<class ItemType>
void L1st<ItemType>::erase()
{
currentjength = 0:
}
// iostream:
tempiate<class ItemType>
ostream& operator (ostream& outs, const L1st<ItemType>& thejist)
{
for (int 1 = 0 ; 1 < thejist.currentjength; i++)
outs theJ i St.item[i] endl;
return outs;
}
} // listsavitch
#endif // LIST_CPP ( ,
// #ifndef... #endif.)


7. - get_element Pair,
.
8. Pair,
.
9. HeterogeneousPair,
Pair, , -
; ,
. 1 2.
- 1, - 2.
- set_element Pair Heteroge-
neousPai : set_f i rst set_second.
- get_element Pair
HeterogeneousPair -
: get_f i rst get_second.
10. ; :
, ?


.

.
651



1. :
temp]ate<class >
max1mum(T f i r s t . second);
// : <.
// first second.

:
tempiate<class >
maximumd f i r s t . second)
{
if (first < second)
return second:
else
return first;
}
2. :
tempiate<class T>
T absoluteCT value);
// : x < -x
// X .
// .

:
tempiate<class >
absoluteCT value)
{
if (value < 0)
return -value;
else
return value;
}
3.
.
4. ). , (
C++), ( class, struct enum,
. .).
5. .
10.10 10, ,
Int BaseType.
:
tempiate<class BaseType>
i n t search(const BaseType a [ ] .
i n t number_used. BaseType target);
// : number_used <= a.
// [0] a[number_used-l] .
652 14.

// , aCindex] == target,
// ; -1.
:
tempiate<class BaseType>
1nt search(const BaseType a[]. int number_used.
BaseType target)
{
int index = 0, found = false;
while ((!found) && (index < number_used))
if (target == a[index])
found = true;
else
i ndex--+;
if (found)
return index;
else
return -1;
}
6. ,
. ,
, ,
.
, <.
7. // iostream cstdlib;
tempiate<class >
Pair<T>:;get_element(int position) const
{
if (position == 1)
return first;
else if (position == 2)
return second;
else
{
cout "Error: Illegal pair position.\n";
exit(l);
}
}
8.
, , (
) , .
tempiate<class >
Pair<T>::Pair()
{
// .

// , first 1
// second 2;
tempiate<class Tl, class T2>
class HeterogeneousPair
653

{
public:
HeterogeneousPai ():

HeterogeneousPairdl first_value. 2 second_value):

void set_first(Tl value):

void set_second(T2 value):

Tl get__first() const:

T2 get_second() const:

private:
Tl first:
T2 second:
}:
- :
tempiate<class Tl. class T2>
HeterogeneousPair<Tl. T2>::HeterogeneousPair()
{
// .
}
tempiate<class Tl. class T2>
HeterogeneousPair<Tl. T2>::HeterogeneousPair
(Tl first_value. T2 second_value)
: first(first_value). second(second_value)
{
// .
}

tempiate<class Tl. class T2>


Tl HeterogeneousPair<Tl. T2>::get_fir$t() const
{
return first:

tempiate<class Tl, class T2>


T2 HeterogeneousPair<Tl. T2>::get_second() const
{
return second:
}

tempiate<class Tl. class T2>


void HeterogeneousPair<Tl. T2>::set_first(Tl value)
{
first = value;
}

tempiate<class Tl. class T2>


654 14.

void HeterogeneousPa1r<Tl, 2>::set_second(T2 value)


{
second = value;

10. .


1. ,
, .
, ;
, ;
-1. .
,
: ,
. ,
.
2. List, 14.4
14.6, .
.
.
, ,
, , -
. :
; ,
; ,
; , ; ,
; , -
( ). (
, , , - 1,
2 . .)
, .
, ,
, .
.
.
3. ,
, . ,
, ~
-1. , 1 . .
. List,
2.
.
655

4. 2 10 dele-
terepeats .
; 10,
.
5. 14.3
.
,
5 10.
, , .
6. ^^
, 13.6.
.
7.
, 13.7.
.
15

,
,
, ,
.

, .
,
. ,
.
.

1 5 . 1 .

, 1 nt doubl ,
, . ,
.
,
- ,
. . 15.1 ,
.

. 15.1 ,
.
, .
, ,
15.1. 657

. 06paTHte ,
, (, 10 "rolls").

head 1 'i~z ~,
1 1:5 ]
10


"jam "
3


"tea" 1
2 1
|
. 1 5 . 1 .

C++. ,
, . 15.1,
:
struct ListNode
{
string item:
int count;
ListNode *link;
}:
typedef ListNode* ListNodePtr;

.
ListNode, ListNodePtr.
, head, ,
-. :
ListNodePtr head;

, ,
ListNode ,
- link ListNode.
, C++ .
,
, .
,
. , 10
, . 15.1, 12.
:
(*head).count = 12;
658 15.

.
head , *head ,
, ( ), "1 Is"
10. , *head, - , -
, 1nt, count. (*head) .count
1 nt . ,
*head, . ,
(*)
(.), ,
, .
, .
C++ ,
.
,
(->).

(
)
(->) ( ),
() -. :
_ ->_
_ ,
() _. ,
:
struct Record
{
i n t number;
char grade;
}:
Record
- 2001 '':
Record *;
= new Record;
p->number = 2001;
p->grade = *A';

,
, ()
. ,
, , :
head->count = 1 2 ;

, , ,
.
15.1. 659

"bagels"
:
head->1tem = " b a g e l s " ;

. 15.2.

head->count = 12:
head->1tem = "bagels"


head ' " 1 head
11 1 "bagels"
10 12

^
"jam " 1 jam
3 1

"tea" "tea"

NULL NULL

. 15.2.

, , ,
, NULL. . 15.1
, C++.
NULL,

.
NULL . -,
-,
. ,
NULL - . -,
. , ,
. 15.2, , NULL,
, .
,
NULL , ,
. NULL
(, iostream cstddef),
#1nclude
. using ,
using namespace std;,
.
660 15.

NULL ,
:
double nhere = NULL:

- there,
NULL. NULL -
.

NULL
NULL , -
, .
- . ,
<1o$tream> <cstddef>.
, NULL.


1. , :
struct Box
{
string name;
1nt number:
Box *next;
}:
typedef Box* BoxPtr;

:
BoxPtr head;
head = new Box;
head->name = "Sally";
head->number = 18;
cout (*head).name endl ;
cout head->name endl;
cout (*head).number endl;
cout head->number endl;

2. , ,
1. , "Sally"
string 18. ,
- next NULL?
3. , ,
1. - head
, , head,

?
15.1. 661

4. :
struct ListNode
{
string item;
i n t count;
ListNode *l1nk:
}:
ListNode *head = new ListNode;

, "Wilbur's brother Orville" -


item , head.


, . 15.2, .
, -
, .
, -
head. , -
, .
, :
- NULL. , ,
, , -
.

. ,
, . 15.2, .
:
struct Node
{
int data;
Node *1ink:
}:
typedef Node* NodePtr;


. - head,
.
NodePtr head;

new,
:
head = new Node;

- :
head->data = 3;
head->link = NULL:
662 15.

, -, ,
NULL,
. :

head
1 Is w
3 i
:<^<<-M<<<<-:-:-:-:':-:-:::\:-:<<:->>yw.:>:- NULL

, ,
. , -
.
.


, ,
.
-,
. ,
. :
void head insert(NodePtr& head, 1nt the number);


,
. - .
, ,
- .

,
new.
, .
, .
,
-. tempptr,
: *temp_ptr. .
' head_1nsert .
1. ,
tempptr. (
. : *temp_ptr.)
2. ,
3. 11 .
4. - head .
15.1. 663

. 15.3 . 2 3
:
temp_ptr->link = head:
head = temp_ptr;

15.1.

\. 2. temp_ptr->link = head;

temp_ptr Lemp pLr- 1;


12 1
^ I
'''-
7
1 ]
head head
1
Lo 15 1
1^:^^^^^^^:

^^ T
3 3 I.
NULL NULL [.

3. head = temp_ptr; 4.

Lfcimp JLt 1
16. 12
^^
w

'r 1r
head head
15 15

^' ^I
3 3
NULL NULL 1
. 15.3.

1 5 . 1 .

struct Node
{
1nt data;
Node *l1nk;

typedef Node* NodePtr;


void head_1nsert(NodePtr& head. 1nt the_number);
/ / ; - head
/ / .
/ / ;
/ / , the_number. ^
664 15.

15.1 ()

void head_1nsert(NodePtr& head. 1nt the_number)
{
NodePtr temp_ptr;
tGmp_ptr = new Node;
temp_ptr->data = the_number:

temp_ptr->l1nk = head;
head = temp_ptr;
}
, ,
, . ,
,
. .
, ,
,
NULL. - head
, , :
head - NULL;
,
, . ,
.
, ,
- ,
. ,
, . , headinsert,
15.1, ,
, .

:
, headinsert
, -
head, tempptr.
:
head = new Node;
head->data = the_number;
, , , ,
head.
, ,
,
head->l1nk

. 15.4 ( 12). :
, 15,
15.1. 665

,
. .
-
,
.

neda 12
7

15 '

>

3
NULL

. 15.4.

, , ,
, .
,
. ,

.
; ,
head.



. Node, . (
THiiaNode 15.1.)
: .
, .
, NULL. ,
, - NULL.
:
NodePtr search(NodePtr head, int target);
// : - head
// . -
// NULL. ,
// head NULL.
// , .
// , NULL.
666 15.

( target)
- here.
( ,
) . ,
here ,
, .
. 15.5.
, , ,
, . ,
.

target 6

1
head
2 ,

)


1 ^

here
^^ 1
here
7 1 1 1 1
1

^^ t
/ 6 1 6

^' 11
3 1 3
NULL 1 NULL

3
head head .")
2

here ^ ^
1 1 1

here )
6 1

>
3 i
NULL NULL

. 15.5.
15.1. 667

search .
1. here
.
while (here , target
here )
{
here .
}
if (, here ' target)
return here;
else
return NULL;
2. here -
, - link ,
here. - link

here->l1nk

, here ,
:
here = here->link;

, .
search .
here = head;

while (here->data != target &&


here->link != NULL)

here = here->l1nk;

if (here->data == target)
return here;
else
return NULL;

while.
, here ,
- here->link NULL.
, .
, ,
. , here NULL,

here->data
here->link

.
668 15.

here NULL, ,
data 11.
. search 15.2.

15.2.

struct Node
{
1nt data;
Node *link:
}:
typedef Node* NodePtr:

NodePtr searchCNodePtr head, 1nt target);


// : - head
// . -
// NULL. ,
// head NULL.
// , .
// , NULL.


I I cstddef:
NodePtr searchCNodePtr head, int target)
{
NodePtr here = head;

if (here == NULL)
{
return NULL; // .
}
else
{
while (here->data != target &&
here->link != NULL)
here = here->link;

if (here->data == target)
return here;
else
return NULL;


, ,
, .
- ,
. .

15.1. 669

.
, -
, . :
_ * 1 t e r ;
for { = Head: i t e r != NULL: i t e r = 1ter->L1nk)
, iter, . .

Head - , Link - -
, .
,
:
NodePtr Iter: // : Node *iter:
for (iter = head: iter != NULL: iter = iter->Link)
cout (iter->data):

Node NodePtr 15.2.



.
, ,
.
, .
, ,
afterme ,
, . 15.6.

^
after me
3

>
..... 5

^
9

>f
18
NULL

. 15.6.

,
, .
670 15.

15.2. , ,
:
void insert(NodePtr after_me. 1nt the_number):
// : after_me .
// : , after_me,
// , the_number.
, headjnsert (. 15.1).
,
, .
. 15.6 C++ :
// :
temp_ptr->link = after_me->link;
// :
after_me->l1nk = temp_ptr:

.
after_me->l 1 .
15.3.
15.3.

struct Node
{
int data;
Node *l1nk;
}:
typedef Node* NodePtr;

void insert(NodePtr after_me. int the_number);


// : after_me .
// : , after_me.
// , the_number.

void insert(NodePtr after_me. int the_number)
{
NodePtr temp_ptr;
temp_Ptr = new Node;
temp_ptr->data = the_number;

temp_ptr->link = after_me->link;
after_me->link = temp_ptr;
}
insert, , ,
, after_me,
. .
head_insert, 15.1.
insert -
, - .
15.1. 671


. 6i>i
,
. ,
after^me,
, .
.
. 15.7.

1. discard
, before
, .

2. before->link = cliscard->link;

iicau

'
1
3. delete discard.
^
before iicau
6

^>;^:^>>:^

discard
~ 3
r
1
>-:-:.:<;-:.;.:.:.:.;.;.>:.::->:->:.:-:::;-

^
^r
5 before
6
NULL

discard / "^^
r' ^
\

5
NULL

. 15.7.

before ( , ) dis
card ( ) ;
:
before->link = d1scard->link:
672 15.

,
. , ,
del ete:
delete discard;

:


headl head2 - headl
, :
head2 = headl;

head2 , ,
.
, . -
, headl, ,
head2, .
headl ,
head2 , ,
. ,
.
12.


5. .
NodeType, PointerType.
.
6. ,
.
?
7. ,
, -:
struct Node
{
double data:
Node *next:
}:
typedef Node* Pointer;
Pointer pi. p2;
15.2. 673

, 1 . ,
1 . (
2
.)
8. , ,
7. , 2 ,
. , , ,
2.
, .
, , -.
9. .
,
,
:
) ;
) ;
) ;
) .

15.2.
.
, 1930

.
,
.

, ,
. , ' ', ' ',
' '. : ' ',
' ', ''. . 15.8.
, , -
, .
- .
. 13 ,

. , , .
674 15.

. ( ,
, 13.)

. 15.8.

: Stack
Stack, ,
15.4. char.
.
:
. ,
. - Stack
push pop.
15.5 , Stack.
,
.
, , , ,
.
15.6 , ,
. - top
.
15.4. Stack
// stack.h.
// Stack.
// .
#ifndef STACK_H
#clef1ne STACK_H
namespace stacksavitch
{
struct StackFrame
{
char data;
15.2. 675

StackFrame *11;
};
typedef StackFrame* StackFramePtr;
class Stack
{
public:
StackO:
// .
StackCconst Stack& a_stack);
// .

-StackO:
//
// .

void push(char thesymbol);


// : , the_symbol.
// .

char ;
// : .
//
// .

bool empty const;


// true, .
// false,
private:
StackFramePtr top;
}:
} // stacksavitch

#endif / / STACKJ

15.5. , Stack
/ / , Stack.
#1nclude <iostream>
finclude "stack.h"
using namespace std;
using namespace stacksavitch;

int mainO
{
Stack s;
char next, ans;
do
cout "Enter a word: ";
cin.get(next):
while (next != '\n')
{
s.push(next);
cin.get(next);
} ^
676 15.

15.5 ()
cout "Written backward that i s :
while ( ! s.empty0 )
cout s.popO;
cout endl:

cout "Aga1n?(y/n): ":


cin ans:
cin.lgnoredOOOO. '\n');
jwhile (ans != 'n* && ans != 'N'):

return 0;
}

Enter a word: straw
Written backward that is: warts
Aga1n?(y/n):
Enter a word: C++
Written backward that is: ++C
Again?(y/n): n

15.6. Stack
// stack..
// Stack.
// Stack stack.h.
#include <iostream>
#include <cstddef>
#include "stack.h"
using namespace std;

namespace stacksavitch
{
// cstddef:
Stack::Stack0 : top(NULL)
{
// .

// cstddef:
Stack::Stack(const Stack& a_stack)
... .

Stack::-Stack
{
char next;
while (! emptyO)
next = popO; // pop delete.
}
// cstddef:
bool Stack::empty const
{
return (top == NULL);
15.2. 677

/ / cstddef:
void Stack::push(char the_symbol)
. . . - push 10.

II lostream:
char Stack::()
{
i f (emptyO)
{
cout "Error: popping an empty stack.\n":
ex1t(l);

char result = top->data;

StackFramePtr temp_ptr;
temp_ptr = top;
top = top->l1nk;

delete temp_ptr:

return result;
}
} // stacksavitch

- push 10.
. - push
headjnsert, 15.1, ,
push head, top.
,
- top, NULL.
- empty .
,
, 11
.
- pop , . ,
resul t
:
char result = top->data;

resul t
top ,
. :
top = top->l1nk;


- tempptr,
delete:
delete temp_ptr;
678 15.

, - pop,
delete.

pop.
.

10. - push Stack,
15.4.
. Stack,
15.4.

(struct)
- .
,
.
,
.
( ,
)
NULL.
.
.



1. Sally
Sally
18
18

, (*head).name head->name,
(*head) .number head->number .
2. :
head->next = NULL;


(*head).next - NULL;

.
3. delete head;

4. head->item = "Wilbur's brother Orville";


679

5. struct NodeType
{
char data;
NodeType *l1nk;
}:
typedef NodeType* PointerType:
6. NULL.
7. 1 = 1-> next:

8. Pointer discard;
discard = p2->next;
// discard .
p2->next = discard->next;

.
,
; delete, :
delete discard;

9. ).
, .
,
.
.
).
10. // cstddef:
void Stack::push(char the_symbol)
{
StackFramePtr temp_ptr;
temp_ptr = new StackFrame;
temp_ptr->data = the_symbol;
temp_ptr->link = top;
top = temp_ptr;
}
11. // cstddef:
Stack::Stack(const Stack& a_stack)
{
if (a_stack.top == NULL)
top = NULL;
else
{
StackFramePtr temp = a_stack.top; // temp
// no a_stack .
StackFramePtr end; // .
end = new StackFrame;
end->data = temp->data;
top = end;
// .
// .

temp = temp->link;
680 15.

while (temp != NULL)


{
end->link = new StackFrame;
end = end->1ink;
end->data = temp->data;
temp = temp->link;
end->link = NULL:
}


1. void,
.
.
,
, . ,
,
.
.
2. merge_lists
-,
i nt. , ,
,
. .
, ,
. ,
, .
- NULL.
3. , ,
.
,
. ,
char '', '' ', :
'', '' '.
, Stack, 15.4.
- add, push,
- remove, pop.
- ,
.
4. ,
.
681

.
1nt int
. / ,
, .
+, - * , .
-
1 nt. ,

. :
, ,
1 nt ,
, int
,
. (
^,
a^:xf.) .
- .
, :
^^ + 1^_^^-1 + . . . + ^
. ,
apc^i ,
:^ + 7^ + 5
:
"4 + 7x^2 + 5
,
, :
"5 - 7"3 + 2x^1 - 8
-7"4 + 5"2 + 9
,
, ;
. .
.
,
^.
, , :
12"8 + "2 +
5. 10 10
.
double. -:
, ; - addltem,
doubl ; - ful 1 (), ,
; , .
682 15.

6. 5 .
List, , 5, -:
ListO ;
double List:: front ;
double List:: back - ;
double List:: current - ;
void List: :advance() - ;
void List:: reset ;
void List: :insert(double after_me. double insert_me)
insert_ine after_me
- count;
int sizeO ;
friend istream& operator (istream& ins. double write_me).
:
node* head;
node* current;
int count;
, , .
(
):
struct node
{
double item;
node *next;
}:

, .
List, .
list.h. #inclu-
de "list.h" , int inain(){}, .
,
.
,
main.
7. 6 (
14).
, .
- .
:
struct Person
{
string name;
string phone_number;
}:
16

-
,
,
. C++
- ,
. 6 ,
.

1 6 . 1 .
- , ,
.

C++
, .
, , ,
.
- - , ,
.
5 , D
: D
. D ,
, D . D ,
.
684 16.

if stream,
1 stream - (, open close).
, 1 (1 stream),
(1 fstream),
- open close, if stream.


, ,
: , -
.
, ,
.
: ,
, ,
.
, ,

. ,
, -,

.
C++ Employee,
( , ,
), ,
. 16.1 16.2
, .
1 6 . 1 . Employee
// employee.h.
// Employee,
//
// , .
#ifndef EMPLOYEE_H
#define EMPLOYEEJ

#1nclude <str1ng>
using namespace std;

namespace employeessavitch
{

class Employee
{
public:
EmployeeO;
Employee(string the_name. string the_ssn):
string get_name() const:
string get_ssn() const:
double get_net_pay() const:
16.1. 685

void set_name(string new_name):


void set_ssn(string new_ssn);
void set_net_pay(double new_net_pay);
void print_check() const:
private:
string name;
string ssn;
double net_pay;

} / / employeessavitch

#endif / / EMPLOYEES

16.2. Ennployee
// : empl..
// Employee.
// Employee employee.h.
#include <string>
#include <cstdlib>
#include <iostream>
#include "employee.h"
using namespace std;

namespace employeessavitch
{
Employee::Employee0 : name("No name yet"). ssn("No number yet"). net_pay(0)
{
// .

Employee::Employee(string the_name, string the_number)


: name(the_name). ssn(the_number). net_pay(0)
{
//

string Employee::get_name const


{
return name;

string Employee::get_ssn() const


{
return ssn;
}

double Employee::get_net_pay const


{
return netj)ay:
}
void Employee::set_name(string new_name)
{
name = new_name;
}
void Employee: :set_ssn(string new_ssn) ly
686 16.

16.2 {)
{
ssn = new_ssn;
}

void Employee::set_net_pay (double new_net_pay)


{
net_pay = new_net_pay:
}

void Employee::print_check const


{
cout "\nERROR: print_check FUNCTION CALLED FOR AN \n"
"UNDIFFERENTIATED EMPLOYEE. Aborting the program.\n"
"Check with the author of the program about this bug.\n";
exit(l):
}
} // employeessavitch

, ,
Employee, ~ ,
,
. , printcheck
,
.
Employee 16.2. ,
,
. ,
Employee, .
, Employee,
- (name, ssn net_pay), -, 1 nt_
check, get_name, set_name ., 16.1.
- - .
HourlyEmployee SalariedEmployee,
Employee, 16.3 16.4. C++ ,
,
, .
HourlyEmployee.

16.3. HourlyEmployee
// hourlyemployee.h.
// HourlyEmployee.
#1fndef HOURLYEMPLOYEEJ
#def1ne HOURLYEMPLOYEEJ

#include <str1ng>
#1nclude "employee.h"

using namespace std;


16.1. 687

namespace employeessavitch
{

class HourlyEmployee : public Employee


{
public:
HourlyEmployeeO;
HourlyEmployee(string the_name. string the_ssn,
double the_wage_rate. double the_hours);
void set_rate(double new_wage_rate):
double get_rate() const;
void set_hours(double hours_worked);
double get_hours() const:
void print_check(); // ,
// ,
private:
double wage_rate:
double hours:

} // employeessavitch

#endif // HOURLYMPLOYEE_H

. 16.4. SalariedEmployee
// salariedemployee.h.
//' SalariedEmployee.
#ifndef SALARIEDEMPLOYEEJ
#define SALARIEDEMPLOYEE_H

#include <string>
finclude "employee.h"

using namespace std:

namespace employeessavitch
{
class SalariedEmployee : public Employee
{
public:
SalariedEmployeeO:
SalariedEmployee (string the_name. string the_ssn.
double the_weekly_salary):
double get_salary() const:
void set_salary(double new_salary):
void printcheckO;
private:
double salary: / / .
};

} // employeessavitch

#endif // SALARIEDEMPLOYEE H
688 16.

, ,
, ,
public :
class HourlyEmployee : public Employee
{
( HourlyEmployee)
- - ( Employee)
- -.
, HourlyEmployee
, wage_rate hours, - name, ssn netjay,
, , ,
Employee. (,
HourlyEmployee) -,
-
. ,
HourlyEmployee -: name, ssn, net_pay, wage_rate hours.
HourlyEmployee Employee -
, - get_name, get_ssn, get_net_pay, set_name, set_ssn, set_
net_pay print_check.
-
-. .
, HourlyEmployee - wa-
ge_rate hours, -, set_rate, get_rate, set_
hours gethours. 16.3. ,

-, .
pr1nt_
check Employee.
,
.


-
- .
. - -
, .
( ,
-, ,
.)

, HourlyEmployee
16.5, -. ,
- ,
16.1. 689

- .
.
16.5. HourlyEmployee
/ / : hourlyemployee.cpp
/ / HourlyEmployee.
/ / HourlyEmployee
/ / hourlyemployee.h.
#1nclude <str1ng>
#1nclucle <1ostream>
#inclucle "hourlyemployee.h"
using namespace std;

namespace employeessavitch
{

HourlyEmployee:-.HourlyEmployeeO : EmployeeO. wage_rate(0). hours(O)


{
// .
}
HourlyEmployee::HourlyEmployee(str1ng the_name. string the_number,
double the_wage_rate. double the_hours)
: Employee(the_name, the_number). wage_rate(the_wage_rate). hours(the_hours)
{
// .
}
void HourlyEmployee::set_rate(double new_wage_rate)
{
wage_rate = new_wage_rate:
}
double HourlyEmployee::get_rate() const
{
return wage_rate:
}

void HourlyEmployee::set_hours(double hours_worked)


{
hours = hours_worked:
}
double HourlyEmployee::get_hours const
{
return hours;

/* set_net_pay print_check.
. , , , .
, C++ print_check
const. */

voi d HourlyEmployee::pri nt_check()


{
set_net_pay( hours * wage_rate); ^
690 16.

16.5 ()
cout "\ \";
cout "Pay to the order of " get_naiTie() endl;
cout "The sum of " get_net__pay() " DollarsVn":
cout "_____ \n";
cout "Check Stub: NOT NEGOTIABLE\n":
cout "Employee Number: " get_ssn() endl;
cout "Hourly Employee. \nHours worked: " hours
" Rate: " wage_rate " Pay: " get_net_pay() endl:
cout " \n";
}
} // employeessavitch


,
, ,
. , ,
, - -
.
, -, .

-
,
.
-. - pr1nt_check
HourlyEmployee,

-, .
print_check HourlyEmployee (.
16.3 16.5).
, Employee, Salaried-
Employee. 16.4. Salaried-
Employee -, - Employee
, SalariedEmployee.
- -
Employee printcheck,
. Sal ari edEmpl oyee
: name, ssn netpay, salary.
, - - Empl oyee
~ SalariedEmployee ,
.
Employee , HourlyEmployee Sala
riedEmployee,
.
Employee.
16.1. 691


, ,
. C++.
HourlyEmployee Employee,
,
Employee. , ,
Employee. HourlyEmployee
Employee. ( , ,
Empl HourlyEmployee, ,
, ,
Hourly Empl .) ,
.
, .

, , .
, -
. Child Ancestor, Grandchild
Child, Grandchild
, Ancestor.


,
, .
-,
,
.
, 16.5.
HourlyEmployee,
:
HourlyEmployee::HourlyEmployee(str1ng the_name.
string the_number. double the_wage_rate.
double the_hours)
: Employee(the_name. the_number).
wage_rate(the_wage_rate). hoursCthe hours)
{
// .
}

HourlyEmployee:: HourlyEmployee. Empl (the_name. the_number)
Employee ,
the_name the_number. ,
-:
wage_rate(the_wage_rate) wage_rate the_wage_
rate. ,
.
692 16.

HourlyEmployee ,
16.5:
HourlyEmployee: :HourlyEmployee() : EmployeeO. wage_rate(0). hours(O)
{
// .
}
-
.
-
.
,

.
HourlyEmployee ( EmployeeO):
HourlyEmployee::HourlyEmployee : wage_rate(0). hours(O)
{
// .
}
.
,
.
- .

, .
,
.
.
(
),
. (
, , .)
,
.
,
, ,
.


.

( ).
, C++
.
16.1. 693

:
-
Hourly Employee (. 16.3 16.5) Emp
loyee (. 16.1 16.2) - name. ,
HourlyEmployee joe("Josephine". "123-45-6789". 0. 0):

joe "Josephine". (
, - ssn "123-45-6789",
- wage__rate hours 0.)
joe.name
"Mighty-Joe", :
joe.set_name("Mighty-Joe");

-, name,
. - name HourlyEmployee
Employee, ,
-
Employee. - ( -)
- ,
, .
HourlyEmployee - name (
Employee),
- .
-
HourlyEmployee: :print_check 16.5:
void HourlyEmployee::pri nt_check()
{
set_net_pay(hours * wage_rate);
cout "\n \n";
cout "Pay to the order of " get_name() endl:
cout "The sum of " get_net_pay() " DollarsXn":
: - netpay
- setnetpay,
:
void HourlyEmployee::print_check()
{ net_pay = hours * wage_rate; // net_pay.
, . - netpay
Employee, HourlyEmployee
, .
- -
Employee. print_check Hourly-
Employee 16.5 ( .)
, name netpay Employee,
, HourlyEmployee:: pri ntcheck
694 16.

name netpay --
get_name get_net_pay. - Empl
.
- (, get_name set_name),
. (, ,
-
. 6.)
-
- .
, ,
: , name ( )
Employee.
, .
- -
, ,
. -
- ,
, -
-,
- , .
, ,
- ,
-
. (,
, ,
-.)

- protected.

: -

, -
( -)
, , -
. - , ,
.
- , ,
, -
, .
. -
,
.
, , ,
, .
16.1. 695

protected
, - -
.
- -,
, .
protected, private public,
.
protected,
, private,
. .
HourlyEmployee, Em
ployee. -
HourlyEmployee: :print_check -
. - Employee
protected, private,
:
void HourlyEmployee::print_check()
// , -
// Employee protected, private.
{
net_pay = hours * wage_rate:
cout "\n \n";
cout "Pay to the order of " name endl:
cout "The sum of " net_pay " DollarsXn";
cout " \n";
cout "Check Stub: NOT NEGOTIABLE\n":
cout "Employee Number: " ssn endl:
cout "Hourly Employee. \nHours worked: " hours
" Rate: " wage_rate " Pay: " net_pay
endl:
cout " \n":
}
- name, netjay ssn Employee
, HourlyEmployee
. ,
Employee, .
-, protected,
. ,
HourlyEmployee PartTimeHourlyEmployee,
- ,
- Employee. PartTimeHourlyEmployee
- name, net_pay ssn. Employee
protected, PartTimeHourlyEmployee
.
, ,
- .
696 16.

,
.

. ,
, , -
private. -
, -
, , .
,
. ,
,
,
.


- protected,
private public,
. -
.
1- : -
protected, private ic,
.
- .
, protected, .
, protected,
. ,
,
-, , .


1. (
#1nclude using):
void show_employee_data(const Employee object);

i n t mainO
{
HourlyEmployee joe("Mighty Joe".
"123-45-6789". 20.50. 40);
SalariedEmployee boss("Mr. Big Shot".
"987-65-4321". 10500.50);
show_employee_data(joe):
show_employee_data(boss);
return 0;

void show_employee_data(const Employee object)


{
cout "Name: " object.get_name() endl;
16.1. 697

cout "Social Security Number: "


object.get_ssn() endl;
}

2. Smart :
class Smart
{
public:
SmartO;
void print_answer() const;
protected:
int a;
int b;
}:
SmartBut (
#include ).
- crazy
bool, - iscrazy ,
bool, .
.
3. SmartBut 2
- iscrazy:
bool SmartBut::is_crazy() const
{
if (a > b)
return crazy:
else
return true;
}
. (,
, .)

-
Hourly Employee (. 16.3)
- set_rate, get_rate, set_hours get_hours. ,
, Employee.
-, (
, setname setssn), . HourlyEmployee
, Empl .
, HourlyEmployee,
,
. , HourlyEmployee,
16.5, -
printcheck. SalariedEmployee,
16.6. , HourlyEmployee SalariedEmployee
printcheck,
.
698 16.

16.7 ,
Hour!Employee SalariedEmployee.

16.6. SalariedEmployee
// : salariedemployee.cpp.
// SalariedEmployee.
// SalariedEmployee
// salariedemployee.h.
#include <iostream>
#include <string>
#include "salariedemployee.h"
using namespace std;

namespace employeessavitch
{
SalariedEmployee::SalariedEmployeeO : EmployeeO. salary(O)
// .

SalariedEmployee::SalariedEmployee(string the_name. string the_number.


double the_weekly_salary)
: Employee(the_name. the_number), salary(the_weekly_salary)

// .

double SalariedEmployee::get_salary const

return salary;

void SalariedEmployee::set_salary(double new_salary)

salary = new_salary;

voi d Sal ari edEmpl oyee:: pri nt__check ()

set_net__pay(sa1 ary);
cout "\n \n";
cout "Pay to the order of " get_name() endl:
cout "The sum of " get_net_pay() " DollarsXn";
cout " \n";
cout "Check Stub NOT NEGOTIABLE \n";
cOut "Employee Number: " get_ssn() endl;
cout "Salaried Employee. Regular Pay: "
salary endl;
cout " \n";
}
} // employeessavitch

16.7.
#include <iostream>
#include "hourlyemployee.h"
#ini lude "salariedemployee.h"
16.1. 699

using std::cout;
using std::endl;
using namespace employeessavitch;

int mainO
{
HourlyEmployee joe;
joe.set_name("Mighty Joe");
joe.set_ssn("123-45-6789");
joe.set_rate(20.50);
joe.set_hours(40):
cout "Check for " joe.get_name()
" for " joe.get_hours() " hours.\n";
joe.print_check():
cout endl:
SalariedEmployee boss("Mr. Big Shot", "987-65-4321". 10500.50):
cout "Check for " boss.get_name() endl;
boss.printcheckO;

return 0;


Check for Mighty Joe for 40 hours.

Pay to the order of Mighty Joe


The sum of 820 Dollars

Check Stub: NOT NEGOTIABLE


Employee Number: 123-45-6789
Hourly Employee.
Hours worked: 40 Rate: 20.5 Pay: 820

Check for Mr. Big Shot

Pay to the order of Mr. Big Shot


The sum of 10500.5 Dollars

Check Stub NOT NEGOTIABLE


Employee Number: 987-65-4321
Salaried Employee. Regular Pay: 10500.5


- ( -)
.
, . -
, ,
, .
-,
.
700 16.



.
.

,
, . ,
HourlyEmployee :
void set_nanie(string f1rst_name. string last_name);
set_name
setname :
void set_name(string new_name);
, -
set_name .
, . Employee HourlyEmployee,
:
void print_check();
HourlyEmployee print^check,
Employee. ,
print_check .
, , ,
, .



, ,
, .
, ,
, .
.
.
Employee (. 16.1)
HourlyEmployee (. 16.3) print_check
. , :
Employee jane_e;
HourlyEmployee sally_h;

jane_e.print_check();
printcheck Employee,
sally_h.print_check();
pr1nt_check HourlyEmployee.
16.2. 701

1 ntcheck Empl
s a l l y h . :
sally_h.Empl::pri nt_check():
, , ,

. 6.


,
const (&).
.

, , .


4. SalariedEmpl Employee, ,
getname printcheck,
print_check.
get_name?
5. TitledEmployee,
Sal ariedEmpl (. 16.4).
- t i t l e string -
g e t t i t l e , string,
- set_title void, string.
, set_name.
. #include
using namespace. TitledEmployee emplo-
yeessavitch.
6. TitledEmployee 5,
- setname.
. #include
.

16.2.
.

.
,
.
702 16.

,
Derived ~ Base,
Base Derived.
, .
, -
. , .
,
( ), -+ .
,
- ,
. - ,
,
( ,
).
(=) .
Base , Derived
, Derived , ,
C++ =
Base.
, , ,
,
, . ,
-, .



.
( )

.

.
, . ,
- .
Deri ved Base,
:
Der1ved& Derived::operator =(const Der1ved& r1ght_s1de)
{
Base::operator =(r1ght_s1de);

-
Base.
- .
16.2. 703

- ,
Derived.

. Derived - Base,

Base, -.

:
Derived::DerivedCconst Derived& object)
: Base(object). ... . ...
{
Base (object)
-,
. , object Deri ved,
Base , ,
Base.
,
.
,
.
,
.


,
.

,
. ,
delete -
, -
.

,
,
. ,
, .


7. ,
. , ,

, ?
704 16.

8. , Ch1 Id Parent, Grand-


chi 1 d Chi 1 d.
.
GrandchiId?
Grandchild?
9. - addvalue, ,
.
.
- numberused
. .
#1nclude <1ostream>
#1nclude <cstdl1b>
using namespace std;

class PartFi1ledArray
{
public:
PartFi1ledArray(int array_size);
PartFi1ledArray(const PartFilledArray& object):
-PartFi lledArrayO;
void operator = (const PartFilledArray& right_side);
void add__value(double new_entry):
// -.
// ,
protected:
double *:
int max_number:
int number_used:
}:
PartFi11edArray::PartFi1ledArray(int array_size)
: max_number(array_size). number_used(0)
{
a = new double[max_number]:
}
( , -
, . ,
,
, .)
10. PartFi 1 ledArray PartFi 1 ledArrayWMax.
- maxvalue
. get max,
.
- add_value ,
int
. ,
. (
-, .)
16.3. 705

16.3.