Learning C++ Farsi
Learning C++ Farsi
www.txt.ir
www.softgozar.com
www.txt.ir
C++
:
-1 : .
... .
-2 :
...
.
2
www.txt.ir
www.softgozar.com
www.txt.ir
-3 :
.
.
RAM
-4 :
.
-5 :
... .
.
www.txt.ir
www.txt.ir
CPU
-6 :
. ) Hard
(Disk DVD CD .
HDD
FDD
CD ROM
CD
www.txt.ir
www.txt.ir
.
.
:
-1
-2
-3
.
.
.
+1300042774
+1400593419
+1200274027
.
.
) ( .
.
BASEPAY
OVERPAY
GROSSPAY
LOAD
ADD
STORE
.
.
5
www.txt.ir
www.txt.ir
. C ...
. .
grosspay = basepay + overtimepay
.
.
.
:
( .
( .
( .
( .
( .
.
: .
-0.
-1 .
-2 .
www.txt.ir
www.txt.ir
-3 .
-4 .
-5 .
-6 5.
-7 .
-8 .
-9.
:
20 .
-0 .
-1 a b .
a+b -2 .
-3 20<a+b 6.
-4 .
-5 7.
-6 .
-7.
.
.
.
:
: 7 50 .
www.txt.ir
www.txt.ir
.
-0.
-1 sum .
-2 index 7 .
-3 index sum
sum .
-4 7 index
index .
-5 index 50 3.
-6 sum .
-7.
sum index
" index 50 " sum
.
.
: 1000 .
www.txt.ir
www.txt.ir
.
.
.
-0.
min -1 .
. i =1 -2
a -3 .
-4 min>a . min = a
. i = i + 1 -5
-6 1000=<i 8.
-7 3.
min -8 .
-9.
. .
. .
.
:
.
-0.
www.txt.ir
www.txt.ir
a -1 b c .
-2 b+c<a 7.
-3 a+c<b 7.
-4 a+b<c 7.
-5 " ".
-6 8.
-7 " ".
-8.
) ( .
.
.
.
.
.
.
10
www.txt.ir
www.txt.ir
: .
C++
C++ :
. .C++ .C++ C++ .
:
.
11
www.txt.ir
www.txt.ir
:
.
: .
:
.
: .
: .
12
www.txt.ir
www.txt.ir
:
.
. .
.
.
13
www.txt.ir
www.txt.ir
Bit : ) (1
) (0 .
Byte :
. . 8
.
:
1 KB = 1024 B = 210 B
1 MB = 1024 KB = 220 B
1 GB = 1024 MB = 230 B
.
.
;
;i1,i2,index
int
i1 i2 index
32767 -32768 .
int .
:
C++ ; .
14
www.txt.ir
www.txt.ir
...
. test1 test!num
mark.1 .
C++
. C++ :
cdecl
char
asm
auto
class
continue const
default _cs
delete
do
double
_ds
else
enum
_es
extern
_export
_fastcall far
float
for
friend
goto
huge
if
inline
int
interrupt
_loadds
long
near
operator new
pascal
protected private
register public
return
_saveregs
_seg
short
sizeof
_ss
static
struct
unsigned union
break
case
signed
template switch
virtual
typedef this
volatile void
while
C++
.
short SHORT shoRT .
.
C++ :
: char -1 ' '.' '1' 'a
-128 127 . char
.
A 65 .
15
www.txt.ir
www.txt.ir
unsigned char
8 bits
0 to 255
char
8 bits
-128 to 127
-32,768 to 32,767
16 bits enum
0 to 65,535
-32,768 to 32,767
16 bits int
-32,768 to 32,767
0 to 4,294,967,295
32 bits long
-2,147,483,648 to 2,147,483,647
32 bits float
64 bits double
16
www.txt.ir
www.txt.ir
. C++
.
)=(
a = 5 5
a .
.:
a=b+5 b + 5 a .
. .
;a,b
;10
;4
;b
;7
int
= a
= b
= a
= b
a 4 b 7 C++ .
:
;)a = 2 + (b = 5
:
;b = 5
;a = 2 + b
17
www.txt.ir
www.txt.ir
7 a .
C++ :
a = b = c = 5
5 a b c .
C++ :
+
% .
:
;a = 11 % 3
a 2 . 2 11 3 .
=. %= /= *= -= +
:
;value=value+increase ;value += increase
18
www.txt.ir
www.txt.ir
;a = a - 5
;a -= 5
;a = a / b
;a /= b
;)price=price*(units+1
;price*=units+1
;)x = x % (y * z
;x %= y * z
) (++
) (-- . ) (++
) (-- .
;a += 1
;a = a + 1
;a++
;++a
.
;a -= 1
;a = a - 1
;a--
;--a
.
a++ ++a ++
. ++ ++
++
. --
. :
;b = 3
;a = ++b
;b = 3
;a = b++
19
www.txt.ir
www.txt.ir
b b 4 4
a b 3 a
b 4 .
6 m :
;a = 2
;b = 3
;m = ++a + b--
b 2 a 3 .
.
;y = 5 * 3 + 2 - 1 * 3 / 2
y 30 24 15.5 . 17.5
y
.
:
-1 .
.
-2 * / % .
.
20
www.txt.ir
www.txt.ir
-3 + - .
.
15.5 .
y = 15.5
;y = 5 * 3 + 2 - 1 * 3 / 2
6
1
4
5
2
3
----
:
x = 14
----
z = 8
----
;x = (2 + 1) * 3 + 5
4
1
2
3
;)z = 5 % 3 * (3 + 1
4
2
3
1
;y = p * r % q + w / x - y
6
1
2
4
3
5
. 5 3
5 3
.
.
.
. ==) ( )!= (
21
www.txt.ir
www.txt.ir
>-----
)(a==5
>-----
)(a*b>=c
>-----
))(b+4<a*c
>-----
))((b=2)==a
= == .
. )) ((b=2)==a 2 b
a .
! || && . ! ) (NOT
. .
.
:
>----
)!(5 == 5
>----
)!(6 <= 4
>----
!0
22
www.txt.ir
www.txt.ir
>----
!1
a&&b
a||b
>-----
))((5==5)&&(3>6
>-----
))((5==5)||(3>6
>-----
))((3-3)&&(3<5
>-----
))((3-3)||(3<5
) a=1 b=2(c=3
>-----
))((b-2*a)&&(c==3
>-----
))((b==2*a)&&(c!=4
>-----
))((c==a+b)||(b<a
>-----
))((b-c==-a)||(b-c==a
23
www.txt.ir
www.txt.ir
. :
: 2 ? 1
1 2
. :
3 7 6 >---
7==6?4:3
6>3?a:b
b a >---
a>b?a:b
:
-1
-2
-3
!
=<
<
=!
=>
>
==
-4
&&
-5
||
?: - 6
:
24
www.txt.ir
www.txt.ir
2 >= 3 && 2 == 2 || 2 != 3
1
4
2
5
3
>----
&&
||
>----
:
))(((2 >= 3) && (2 == 2)) || (2 != 3
.
.
25
www.txt.ir
www.softgozar.com
www.txt.ir
C++ cin
cout .
.
cout
cout << .
;"cout << "This is a test
This is a test .
;cout << 5120
5120 .
;cout << x
x .
<<
. ) (This is a test
) (5120 ) (x .
This is a test )"(
)"(
. :
;"cout << " Hello
Hello :
26
www.txt.ir
www.txt.ir
Hello .
:
;"cout << "Hello," << "I am" << "new in C++
cout
:
;"cout << "This is a text.
;"cout << "This is another text.
cout
:
This is a text. This is another text.
27
www.txt.ir
www.txt.ir
\n
. :
;"cout << "First sentence.\n
;"cout << "Second sentence.\n Third sentence.
:
First sentence.
Second sentence.
Third sentence.
\n endl
:
;cout << "First sentence." << endl
;cout << "Second sentence." << endl
:
First sentence.
Second sentence.
cin
cin >> .
;int age
;cin >> age
age
age cin .
28
www.txt.ir
www.txt.ir
Enter .
16 age 16
Enter .
<<
. cin
.
:
;cin >> a >> b
;cin >> a
;cin >> b
.
.
//first program in C++
>#include <iostream.h
)( int main
{
;"cout << "Hello, This is a C++ program.
;return 0
}
29
www.txt.ir
www.txt.ir
C++
.
C++ C++
" "http://www.tehranedu.com/subparts/elearning/c/tcp/tcp.exe
. .
save tcp.exe
. MB3.5 10 20
) ( .
tcp .
C++ tcp :
30
www.txt.ir
www.txt.ir
unzip
.
OK Close .
C++
""c:\tcp
" "c:\tcp\bin tc
. C++ .
31
www.txt.ir
www.txt.ir
.
.
Ctrl F9
) .(Ctrl + F9 .
C++ .
Alt F5 ) . (Alt + F5
:
Hello, This is a C++ program.
. C++
.
C++
32
www.txt.ir
www.txt.ir
) (Ctrl + F9
.
C++
)F9
(Ctrl
C++
C++ .
.
//first program in C++
.
// C++ .
C++ .
// * / */ .
.
/* This is a comment line.
This is another comment line. */
.
>#include <iostream.h
# .
.
33
www.txt.ir
www.txt.ir
iostream.h . iostream.h
) cin (cout .
) (int main
. main
C++ . main .
main C++
. main ) ( main
. C++ )
... ( . main
} { .
;"cout << "Hello, This is a C++ program.
" "
.
> #include<iostream.h .
C++ ) ; ( .
;return 0
main
. .
C++
.
: C++ .
.
34
www.txt.ir
www.txt.ir
cout
.
cin
.
// Addition program.
#include <iostream.h>
// function main begins program execution
int main()
{
int integer1; // first number to be input by user
int integer2; // second number to be input by user
int sum; // variable in which sum will be stored
cout << "Enter first integer\n"; // prompt
cin >> integer1; // read an integer
cout << "Enter second integer\n"; // prompt
cin >> integer2; // read an integer
sum = integer1 + integer2; //assignment result to sum
cout << "Sum is " << sum << endl; // print sum
return 0; // indicate that program ended successfully
} // end function main
.
:
35
www.txt.ir
www.txt.ir
>#include <iostream.h
)(int main
{
;"cout << "Enter first integer\n
;int integer1
;cin >> integer1
;"cout << "Enter second integer\n
;int integer2
;cin >> integer2
;int sum
36
www.txt.ir
www.txt.ir
. .
.
.
;"cout << "Enter first integer \n
Enter integer1
.
;"cout << "Enter second integer \n
;cin >> integer2
37
www.txt.ir
www.txt.ir
integer1 integer2
)=( sum .
;cout << "Sum is " << sum << endl
.
:
if
. "
".
. if :
) ( if
;
:
)if (x == 50
;"cout << "x is 50
x 50
" "x is 50 cout << "x is
; " 50 .
38
www.txt.ir
www.txt.ir
if .
.
} { :
) if ( x==50
{
;" cout << "x is
;cout << x
}
x 50 " "x is 50
.
39
www.txt.ir
www.txt.ir
)if ( x == 50
;" cout << "x is
; cout << x
. x 50
" "x is 50 x 20 20
. ; x>> cout if
.
. .
if/else
.
C++
.
) ( if
; 1
else
40
www.txt.ir
www.txt.ir
; 2
1 2 .
:
) if ( x = = 50
;"cout << "x is 50
else
;"cout << "x is not 50
50 " "x is 50
" "50 x is not .
} {
. :
) if ( x > 50
{
;cout << x
;"cout << "is greater than 50
}
else
{
;cout << x
41
www.txt.ir
www.txt.ir
x 100 :
100 is greater than 50
x 10 :
10 is less than 50
if/else .
:
>#include <iostream.h
) (int main
{
;int x
;"cout << "Please enter a number:
;cin >> x
) if ( x > 0
;"cout << x << "is positive.
42
www.txt.ir
www.txt.ir
else
) if ( x < 0
;"cout << x << "is negative.
else
;"cout << "The number that you entered is 0.
;return 0
}
. :
Please enter a number : 10
10 is positive.
Please enter a number : -5
-5 is negative.
Please enter a number : 0
The number that you entered is 0.
: if if/else
. if
:
) if ( x > 0
43
www.txt.ir
www.txt.ir
:
) if ( x > 0
;"cout << x << "is positive.
switch
if if/else .
. C++
switch :
) ( switch
{
: case 1
1
;break
: case 2
2
;break
.
.
.
: n
case
n
;break
default :
}
44
www.txt.ir
www.txt.ir
switch :
switch 1
. 1
break break switch
. 1 switch
2 2
. .
) default ( .
:
>#include <iostream.h
) (int main
{
;int x
;"cout << "Please enter a number:
;cin >> x
{ )switch (x
case 1:
;"cout << "x is 1
;break
case 2:
;"cout << "x is 2
;break
default:
;"cout << "Unknown value
}
;return 0
}
. :
Please enter a number:1
x is 1
Please enter a number:2
45
www.txt.ir
www.txt.ir
x is 2
Please enter a number:5
Unknown value
switch if/else .
switch if/else :
)if (x == 1
;"cout << "x is 1
else
)if (x == 2
;"cout << "x is 2
else
;"cout << Unknown value
default switch
.
break
switch break
. .
.
>#include <iostream.h
) (int main
{
;int x
;"cout << "Please enter a number:
46
www.txt.ir
www.txt.ir
;cin >> x
{ )switch (x
case 1:
case 2:
case 3:
;")cout << "x is (1 or 2 or 3
;break
default:
;")cout << "x is not (1 or 2 or 3
}
;return 0
}
. :
a number:1
)or 3
a number:2
)or 3
a number:5
Please enter
x is (1 or 2
Please enter
x is (1 or 2
Please enter
while
) (
. :
.
.
. "
" . )
( " " .
. )
47
www.txt.ir
www.txt.ir
( .
while .
) ( while
{
}
.
2 1000
. .
>#include <iostream.h
) (int main
{
;int product = 2
)while (product <= 1000
;product = 2 * product
" cout << "The first power of 2 larger than 1000 is
;<<product <<endl
;return 0
}
product 2 .
while product=2*product product
product 1024 2
1000 .
The first power of 2 larger than 1000 is 1024
48
www.txt.ir
www.txt.ir
: while }{
}{ .
: .
>#include <iostream.h
) (int main
{
;int n=1, sum=0
)while (n <= 100
{
;sum += n
;// sum = sum + n
;++n
;// n = n + 1
}
;cout << "1 + 2 + ... + 100 =" <<sum << endl
;return 0
}
49
www.txt.ir
www.txt.ir
100 n sum n
n 101
) (100=> n while
cout .
1 + 2 + ... + 100 =5050
n .
.
sum .
.
:
. -1 .
>#include <iostream.h
) (int main
;{ int num, counter = 0
;float average, sum = 0
;"cout << "Enter a number (-1 to end):
;cin >>num
{)while (num != -1
;sum += num ; // sum = sum + sum
;++counter
;"cout << "Enter a number (-1 to end):
;cin >> num
}
50
www.txt.ir
www.txt.ir
{)if (counter != 0
;average = sum / counter
;cout << "The average is " << average << endl
}
else
;cout << "No numbers were entered." << endl
;return 0
}
.
end):20
end):50
end):65
end):70
end):90
end):100
end):1
end):6
end):-1
(-1 to
(-1 to
(-1 to
(-1 to
(-1 to
(-1 to
(-1 to
(-1 to
(-1 to
50.25
Enter a number
Enter a number
Enter a number
Enter a number
Enter a number
Enter a number
Enter a number
Enter a number
Enter a number
The average is
-1
. num
. counter
sum average
. if
cin -1
:
Enter a number (-1 to end): -1
do/while
51
www.txt.ir
www.txt.ir
:
>#include <iostream.h
)(int main
{
;int counter = 1
{ do
;" " << cout << counter
;) }while ( ++counter <= 10
;cout << endl
;return 0
}
1 10 .
counter 10
.
1 2 3 4 5 6 7 8 9 10
52
www.txt.ir
www.txt.ir
:
. .
#include <iostream.h>
int main( )
{
float mark;
int howmany,counter=1;
int passes=0,failures=0;
cout << "How many marks : ";
cin >> howmany;
do {
cout << "Enter mark "<<counter<<" : ";
cin>>mark;
if (mark>=10)
++passes;
else
++failures;
53
www.txt.ir
www.txt.ir
:
How many marks : 10
Enter mark 1 : 18
Enter mark 2 : 15
Enter mark 3 : 9
Enter mark 4 : 17.5
Enter mark 5 : 9.75
Enter mark 6 : 8
Enter mark 7 : 11
Enter mark 8 : 13
Enter mark 9 : 5
Enter mark 10 : 13
Passed : 6
for
for . for
. for
:
)
; ;
( for
{
}
54
www.txt.ir
www.txt.ir
for while
1 5 :
>#include <iostream
)(int main
{
;int counter = 1
{ ) while ( counter <= 5
;cout << counter << endl
;++counter
}
;return 0
}
for counter
1 . ) (5=>counter
counter 1 cout
1 . counter++
counter .
cout .
55
www.txt.ir
www.txt.ir
counter 6
.
1 2 3 4 5
for :
)for(int counter=10; counter>=1; counter=counter-2
10 1 :
10 8 6 4 2
counter=counter-1
counter -= 2 .
: 1 100 .
>#include <iostream.h
) ( int main
;{ int sum = 0
56
www.txt.ir
www.txt.ir
for ) ( ,
:
;for (int num = 2
;num <= 100
;)sum += num, num +=2
.
.
: 2
.
>#include <iostream.h
) (int main
{
;unsigned long int x=1
;int power
;"cout << "Enter power:
;cin >>power
)for (int counter=1;counter<=power;counter++
;x*=2
;cout << "2 ^ " << power << " = " << x <<endl
;return 0
57
www.txt.ir
www.txt.ir
}
Enter power:25
2 ^ 25 = 33554432
for } { for
} {
.
: X55 .
>#include <iostream.h
) (int main
{
)for (int x=1;x<=5;x++
{
)for (int y=1;y<=5;y++
;"cout <<x*y<<"\t
;cout<<endl
}
;return 0
}
:
5
10
15
20
25
4
8
12
16
20
3
6
9
12
15
2
4
6
8
10
1
2
3
4
5
x for cout } {
. y cout .
;" t\">>x*y>>cout \t . \t
58
www.txt.ir
www.txt.ir
. .
for for
.
; endl>> cout
:
10
20
8
16
6
12
4
8
2
4
5
15
25
4
12
20
3
9
15
2
6
10
1
3
5
:
. Ctrl Break
) (Ctrl+Break C++
. .
break continue
break while do/while for switch
. :
>#include <iostream.h
)(int main
{
;int n
)for (n=10; n>0; n--
{
;"cout << n << ",
)if (n==3
{
;"!cout << "countdown aborted
59
www.txt.ir
www.txt.ir
;break
}
}
;return 0
}
:
!10,9,8,7,6,5,4,3,countdown aborted
10 4 n 3
.
: n for .
.
continue while do/while for
. while
do/while continue
for .
while do/while continue
. 1 20 10
.
>#include <iostream.h
) (int main
{
;int n=0, sum=0
)while (n < 20
{
;++n; // n = n + 1
60
www.txt.ir
www.txt.ir
.
1+2+ ...(except 10)...+20=200
10 n 10
n
.
.
. y = 2x + 1
y (f(x f(x) = 2x + 1 .
f ) ( 2
. .
61
www.txt.ir
www.txt.ir
:
f(0) = 2 * (0) + 1 = 1
f(1) = 2 * (0) + 1 = 3
f(-1) = 2 * (-1) + 1 = -1
f .
: .
2s = 3.14*r
:
s(r) = 3.14*r2
. :
=>, x
62
www.txt.ir
www.txt.ir
0
= )abs(x
= ||x
-x
,
x<0
=)
(abs
:
abs(1) = 1
abs(-1) = 1
abs(0) = 0
. :
f(x,y) = x + y
. :
=)=x+y
(f
f(1,2) = 1+2 = 3
f(2,3) = 2+3 = 5
f(1,-1) = 1+(-1) = 0
... . .
63
www.txt.ir
www.txt.ir
C++
C++
sqrt . :
;)cout << sqrt (900
30 . 900 sqrt .
:
>#include <math.h
math.h .
:
>#include <iostream.h
>#include <math.h
) ( int main
{
;int x = 30
;double y = 5
;cout << sqrt (x+2*y+9)<<endl
;return 0
}
7 sqrt 30+2*5+9=49
.
.
) fabs(x x .
64
www.txt.ir
www.txt.ir
fabs(1.2) = 1.2
fabs(-1.2) = 1.2
fabs(0) = 0
=)
-1
(fabs
x .
sqrt(9) = 3
sqrt(2) = 1.414214
)sqrt(x
=)
(sqrt
x y .
pow(2, 5) = 32
pow(2, 0.5) = 1.414214
)pow(x,y
=)
(pow
e e.
2.71828 .
)exp(x
exp(2) = 7.38906
=)
(exp
x .
e . exp .
log(2.71828) = 1
log(7.389050) = 2
)log(x
)log10(x
2.71828
=)
(log
10 x . )log10(100
10 100 2
65
www.txt.ir
www.txt.ir
log10(100)=2
log10(10) = 1
log10(1000) = 3
10
=)
(log10
x/y .
fmod(13.657,2.333) = 1.992
)fmod(x,y
=)
4.2
5.1
(fmod
x
.
ceil(9) = 9
ceil(9.2) = 9
ceil(-9.8) = -9
)ceil(x
2.4
=)
(ceil
.
x .
floor(7) = 7
floor(7.3) = 7
floor(-7.2) = -8
)floor(x
=)
2.4
(floor
sin x x). (
sin(0) = 0
sin(3.14/2) = 1
)sin(x
1.57079
=)
(sin
66
www.txt.ir
www.txt.ir
cos x x). (
cos(0) = 1
cos(3.14/2) = 0
)cos(x
1.57079
=)
(cos
tan x x). (
tan(0) = 0
tan(3.14/4) = 1
)tan(x
0.78539
=)
(tan
arcsin x . x
-1 1 . .
asin(0) = 0
asin(1) = 1.570796
)asin(x
=)
(asin
arccos x . x
-1 1 . .
acos(1) = 0
acos(0) = 1.570796
)acos(x
=)
(acos
arctan x .
.
atan(1) = 0.785398
atan(0) = 0
atan(21584.891) = 1.570795
)atan(x
=)
(atan
67
www.txt.ir
www.txt.ir
: .
.
D
_____
R
=
180o
_____
3.14
D R
. :
45o
_____
====> R=0.785
o
R
=
180
3.14
D
_____
====> D=90o
o
180
_____
1.57
=
_____
3.14
68
www.txt.ir
www.txt.ir
#include <iostream.h>
#include <math.h>
int main( )
{
float r;
for (int d=2;d<=90;d+=2)
{
r = 3.1415 * d / 180;
cout<<"sin("<<d<<")="
<<floor(sin(r)*1000 + 0.5)/1000;
cout<<"\tcos("<<d<<")="
<<floor(cos(r)*1000 + 0.5)/1000;
cout<<"\ttan("<<d<<")="
<<floor(tan(r)*1000 + 0.5)/1000;
cout<<endl;
}
return 0;
}
:
sin(2)=0.035
sin(4)=0.07
sin(6)=0.105
sin(8)=0.139
sin(10)=0.174
sin(12)=0.208
sin(14)=0.242
.
.
.
sin(86)=0.998
sin(88)=0.999
sin(90)=1
cos(2)=0.999
cos(4)=0.998
cos(6)=0.995
cos(8)=0.99
cos(10)=0.985
cos(12)=0.978
cos(14)=0.97
.
.
.
tan(2)=0.035
tan(4)=0.07
tan(6)=0.105
tan(8)=0.141
tan(10)=0.176
tan(12)=0.213
tan(14)=0.249
.
.
.
cos(86)=0.07
cos(88)=0.035
cos(90)=0
tan(86)=14.292
tan(88)=28.599
tan(90)=21584.891
r = 3.1415 * d / 180
floor(sin(r)*1000 + 0.5)/1000
69
www.txt.ir
www.txt.ir
.
. )) sqrt(pow(2,2 2
.
.
.
. C++
. main
. C++
.
.
C++ :
) (
{
}
70
www.txt.ir
www.txt.ir
.
:
>#include <iostream.h
)long int power2 (int x
{
;long int y
;y=x*x
;return y
}
)( int main
{
)for (int i=1;i<=10;i++
;" "<<)cout<<power2(i
;return 0
}
1 10 .
1 4 9 16 25 36 49 64 81 100
) power2(x ) pow(x,2
C++ . 2f(x) = x .
) (int ) (int long . )power2(i
i x .
y x*x y y
cout .
i for 10
x y main i power2 .
71
www.txt.ir
www.txt.ir
:
.
:
. .
#include <iostream.h>
int maximum (int x,int y, int z)
{
int max=x;
if (y>max)
max=y;
if (z>max)
max=z;
return max;
}
int main ()
{
int num1,num2,num3;
cout << "Enter three numbers: ";
cin >> num1 >> num2 >> num3;
cout << "Max is :"
<< maximum(num1,num2,num3)<<endl;
cout << "Max of 5,20,1 is "
<< maximum(5,20,1)<<endl;
return 0;
}
Enter three numbers: -5 20 150
Max is :150
Max of 5,20,1 is 20
72
www.txt.ir
www.txt.ir
main . main .
main .
.
.
main
. . :
;)
);( .
power2 :
;) long int power2( int
maximum :
;) int maximum( int, int, int
73
www.txt.ir
www.txt.ir
: maximum
#include <iostream.h>
int maximum (int ,int,int);
int main ()
{
int num1,num2,num3;
cout << "Enter three numbers: ";
cin >> num1>>num2>>num3;
cout << "Max is :"
<< maximum(num1,num2,num3)<<endl;
cout << "Max of 5,20,1 is "
<< maximum(5,20,1)<<endl;
return 0;
}
int maximum (int x,int y, int z)
{
int max=x;
if (y>max)
max=y;
if (z>max)
max=z;
return max;
}
Enter three numbers: -5 20 150
Max is :150
Max of 5,20,1 is 20
maximum main
. maximum
74
www.txt.ir
www.txt.ir
: .
.
.
.
.
. .
:
2 , 5 , 11 , 23 , ...
.
2*23+1=47 :
2
d1
dn = 2*dn-1+1
2
. :
2
)d(1
d(n) = 2*d(n-1)+1
d(1)=2
d(n) = 2*d(n-
. 1)+1 .
75
www.txt.ir
www.txt.ir
.
: C++
long int d(long int n)
{
if (n == 1)
return 2;
else
return 2*d(n-1)+1;
}
. 20
#include <iostream.h>
long int d(long int);
int main( )
{
for (int i=1;i<=20;i++)
{
cout<<d(i)<<"\t";
if (i%5==0) cout<<endl;
}
return 0;
}
long int d(long int n)
{
if (n == 1)
return 2;
else
return 2*d(n-1)+1;
}
2
95
3071
98303
5
191
6143
196607
11
383
12287
393215
23
767
24575
786431
47
1535
49151
1572863
76
www.txt.ir
www.txt.ir
.
)(Towers of Hanoi
.
.
.
64
. .
. .
64
. .
77
www.txt.ir
www.txt.ir
.
. n
:
-1 n-1 .
-2 ) ( .
n-1 -3 .
n=1
. n=1 .
.
-1
-2
-3
-4
:
>#include <iostream.h
78
www.txt.ir
www.txt.ir
:
Moving disks form
How many disks do
Disk 1 from tower
Disk 2 from tower
Disk 1 from tower
Disk 3 from tower
Disk 1 from tower
Disk 2 from tower
Disk 1 from tower
Disk 4 from tower
tower A to C.
you want to move?4
A to tower B
A to tower C
B to tower C
A to tower B
C to tower A
C to tower B
A to tower B
A to tower C
79
www.txt.ir
www.softgozar.com
www.txt.ir
C
A
A
C
B
C
C
tower
tower
tower
tower
tower
tower
tower
to
to
to
to
to
to
to
B
B
C
B
A
A
B
tower
tower
tower
tower
tower
tower
tower
from
from
from
from
from
from
from
1
2
1
3
1
2
1
Disk
Disk
Disk
Disk
Disk
Disk
Disk
0
.
.
.
C++ )( rand stdlib.h
. :
80
www.txt.ir
www.txt.ir
;)(i = rand
1 32767 i . )( rand
.
rand
.
. 31250 1 6 .
6 0 5 .
1 1 6 .
1 32767 :
31250
=a
=a%6+1
1 6 ] [a,b
.
rand()%(b-a+1)+a
] [20,100 .
;int a = 20 , b = 100
;cout<< rand()%(b-a+1)+a
20 1 6 . 20
:
81
www.txt.ir
www.txt.ir
>#include <iostream.h
>#include <stdlib.h
)(int main
{
) for (int i = 1; i<= 20; i++
{
;"cout << rand() % 6 + 1<<"\t
) if ( i % 5 == 0
;cout << endl
}
;return 0
}
:
5
5
2
6
5
5
1
4
3
2
2
4
5
4
3
1
5
2
5
5
.
. )( rand
.
.
)( rand )( srand .
)( rand
)( srand .)( srand stdlib.h
. )( srand .
>#include <iostream.h
>#include <stdlib.h
)(int main
82
www.txt.ir
www.txt.ir
{
unsigned int num;
cout<<"Enter a number: ";
cin>>num;
srand(num);
for (int i = 1; i<= 20; i++ )
{
cout << rand() % 6 + 1<<"\t";
if ( i % 5 == 0 )
cout << endl;
}
return 0;
}
.
Enter a number:
3
4
6
4
5
3
1
6
Enter a number:
1
4
2
6
4
2
4
4
Enter a number:
3
4
6
4
5
3
1
6
251
1
6
1
6
350
3
2
5
5
251
1
6
1
6
4
2
4
6
6
5
5
1
4
6
3
2
1
2
5
3
4
2
4
6
6
5
5
1
.
.
83
www.txt.ir
www.txt.ir
time time.h . time
:
;))srand(time(0
)( rand .
.
>#include <iostream.h
>#include <stdlib.h
>#include <time.h
)(int main
{
;))srand(time(0
) for (int i = 1; i<= 20; i++
{
;"cout << rand() % 6 + 1<<"\t
) if ( i % 5 == 0
;cout << endl
}
;return 0
}
: 2000
.
>#include <iostream.h
>#include <stdlib.h
>#include <time.h
)(int main
{
;int back=0,front=0,face
84
www.txt.ir
www.txt.ir
;))srand(time(0
) for (int i = 1; i<= 2000; i++
{
;face=rand()%2+1
)switch(face
{
case 1:
;++back
;break
case 2:
;++front
;break
default:
;"!cout<<"Error
}
}
;cout<<"Front: "<< front<<endl
;cout<<"Back : "<< back<<endl
;return 0
}
enum
enum
. .
... 2 {1 }n enum
1 2 ... n 0 n .
.
}enum TrueFalse {FALSE , TRUE
85
www.txt.ir
www.txt.ir
FALSE TRUE 1 .
:
}enum Days {SAT = 1, SUN, MON, TUE, WED, THU, FRI
1 7 .
. enum .
.
1 7 .
.
}enum Days { MON, TUE, WED, THU, FRI, SAT , SUN = 0
GRAY 6
BLUE = 5 .
. :
;tf1,tf2
;day1, day2 = SUN
TrueFalse
Days
86
www.txt.ir
www.txt.ir
Colors
. :
;TrueFalse {FALSE, TRUE} tf1 ,tf2
: enum
. :
;}enum MyEnum {ALPHA, BETA, GAMMA
int
;i = BETA
int
;j = 3+GAMMA
1 i 5 j .
;}enum MyEnum {ALPHA, BETA, GAMMA
;MyEnum x = 2
;MyEnum y = 123
.
.
enum .
>#include <iostream.h
)(int main
{
;}enum PizzaSize{SMALL,MEDIUM,LARGE,EXTRALARGE
;PizzaSize size
;size=LARGE
;cout<<"The small pizza has a value of "<<SMALL
;cout<<"\nThe medium pizza has a value of "<<MEDIUM
87
www.txt.ir
www.txt.ir
:
The small pizza has a value of 0
The medium pizza has a value of 1
. C++
void .
void . .
)void function (int num
{
;cout << "My input is" << num << endl
}
return
.
.
void main void .
;return 0 :
)(void main
{
}
88
www.txt.ir
www.txt.ir
void
.
>#include <iostream.h
;)void hanoi(int, char, char, char
) (void main
{
;cout<<"Moving 4 disks form tower A to C."<<endl
;)'hanoi(4,'A','B','C
}
{ )void hanoi(int n, char first, char help, char second
{ )if (n == 1
cout << "Disk " << n << " from tower " << first
;<< " to tower " << second << endl
{ } else
;)hanoi(n-1, first, second, help
cout << "Disk " << n << " from tower " << first
;<< " to tower " << second << endl
;)hanoi(n-1, help, first, second
}
}
hanoi return
void
. .
void
.
;)(void function1
;)int function2(void
89
www.txt.ir
www.txt.ir
function1 .
function2
:
>#include <iostream.h
;)int function(void
) (void main
{
;int num, counter = 0
;float average, sum = 0
;)(num=function
{)while (num != -1
; sum += num
;++counter
;)(num=function
}
{)if (counter != 0
;average = sum / counter
;cout << "The average is " << average << endl
}
else
;cout << "No numbers were entered." << endl
}
{)int function(void
;int x
;"cout << "Enter a number (-1 to end):
;cin >>x
;return x
}
function
.
90
www.txt.ir
www.txt.ir
)( num=function num
while .
while
function
.
.
C++ ) { ( ) } (
.
. :
>#include <iostream.h
) (void main
{
{
;int x= 1
;cout << x
}
;cout << x
}
91
www.txt.ir
www.txt.ir
. :
>#include <iostream.h
;int x=1
;)(int f
) (void main
{
;cout << x
;)(cout << f
;cout << x
}
{)(int f
;return 2*x
}
x . main f .
.
121
.
.
.
c++
static . static .
:
;static int x=1
92
www.txt.ir
www.txt.ir
x
.
:
>#include <iostream.h
;)(int f
) (void main
{
;)(cout << f
;)(cout << f
;)(cout << f
}
{)(int f
;static int x=0
;x++
;return x
}
:
123
f x 0 x
. 1 .
f x 1
. 2
f 3 . static
111 .
. :
93
www.txt.ir
www.txt.ir
>#include <iostream.h
) (void main
{
;int x=1
;cout << x
{
;int x= 2
;cout << x
}
;cout << x
}
x main .
:
121
x
.
x .
x main
x . x
.
.
.
>#include <iostream.h
void useLocal( void ); // function prototype
void useStaticLocal( void ); // function prototype
void useGlobal( void ); // function prototype
94
www.txt.ir
www.txt.ir
95
www.txt.ir
www.txt.ir
:
local x in main's outer scope is 5
local x in main's inner scope is 7
local x in main's outer scope is 5
local x is 25 on entering useLocal
local x is 26 on exiting useLocal
96
www.txt.ir
www.txt.ir
www.txt.ir
www.txt.ir
.
x 51 .
useGlobal . x
x .
x . 10 .
useGlobal x 100 .
x main
5 main
.
.
.
.
.
.
) ( .
.
. .
>#include <iostream.h
98
www.txt.ir
www.txt.ir
.
The default box volume is: 1
The volume of a box with length 10,
width 1 and height 1 is: 10
The volume of a box with length 10,
width 5 and height 1 is: 50
99
www.txt.ir
www.txt.ir
boxVolume 1
.
.
boxVolume :
;) int boxVolume (int = 1 , int = 1 , int = 1
boxVolume
1 .
length width
height . width length
height .
.
length
boxVolume
length width
length width height
.
100
www.txt.ir
www.txt.ir
. C++ ) (::
.
.
.
) (::
.
.
) (:: .
>#include <iostream.h
;float pi=3.14159
) (void main
{
;int pi=::pi
;cout << "Local pi is : " << pi << endl
;cout << "Global pi is : " << ::pi << endl
}
:
Local pi is : 3
Global pi is : 3.14159
pi float pi
int pi . pi
) (:: . pi
cout pi 3 pi
3.14159 .
101
www.txt.ir
www.txt.ir
.
maximum :
;int a=5, b=6, c=7, max
;)max = maximum(a,b,c
a b c 5 6
7 . .
maximum x y z
5 6 7 x y z
a b c . a b c
.
maximum a .
.
)&(
)&( .
.
102
www.txt.ir
www.txt.ir
>#include <iostream.h
;) & void duplicate (int & , int
) ( void main
{
; int a=1 , b=2
;cout << "a = " << a << " and b = " << b << endl
;)duplicate (a,b
;cout << "a = " << a << " and b = " << b << endl
}
)void duplicate (int &x , int &y
{
;x*=2
;y*=2
}
a = 1 and b = 2
a = 2 and b = 4
a b .
a b
;x*=2
;y*=2
a b . x y a
b .
103
www.txt.ir
www.txt.ir
.
: .
.
>#include <iostream.h
;)& void change (int & , int
) ( int main
{
; int a=1 , b=2
<< cout << "a is " << a << " and b is " << b
;endl
;)change (a,b
<< cout << "a is " << a << " and b is " << b
;endl
;return 0
}
)void change (int &x , int &y
{
;int temp
;temp = y
;y = x
;x = temp
}
:
a is 1 and b is 2
a is 2 and b is 1
104
www.txt.ir
www.txt.ir
a b change
.
prevnext
.
>#include <iostream.h
;)& void prevnext (int ,int & , int
) ( void main
{
; int x = 100 , y , z
" cout << "The input of prevnext function is
;<< x << endl
; )prevnext (x,y,z
;cout << "previous =" << y <<",Next =" << z
}
)void prevnext (int input , int & prev , int & next
{
; prev = input - 1
; next = input + 1
}
.
The input of prevnext function is 100
previous =99,Next =101
input x
prev next y z .
prev next y z .
) (
105
www.txt.ir
www.txt.ir
C++
.
.
. C++
. .
.
>#include <iostream.h
;) int square( int
;) double square( double
)(void main
{
// calls int version
;) int intResult = square( 7
// calls double version
;) double doubleResult = square( 7.5
" "\nThe square of integer 7 is
intResult
" "\nThe square of double 7.5 is
doubleResult
;endl
<< cout
<<
<<
<<
<<
} // end main
// function square for int values
) int square( int x
{
" cout <<"Called square with int argument:
;<< x << endl
;return x * x
} // end int version of function square
// function square for double values
106
www.txt.ir
www.txt.ir
.
Called square with int argument: 7
Called square with double argument: 7.5
The square of integer 7 is 49
The square of double 7.5 is 56.25
( double) ( int)
: . square
int intResult = square (7) ;
: square
int square (int) ;
:
double doubleResult = square (7.5) ;
: square
double square (double );
107
www.txt.ir
www.txt.ir
.
: .
.
.
.
.
.
.
. :
;]
6 num int .
;]int num [6
108
www.txt.ir
www.txt.ir
. 2 -23560 0
.
a 2 b 3 :
;num [a+b] + = 3
] num [5 3 .
:
;cout << num[0] + num[1] + num[2] << endl
2 x
:
;x = num[3]/2
: ) (
.
. num[3]=-
50 ) ( num[4]=32500 .
:
; ]int b[100] , x[27
100 b 27
x .
109
www.txt.ir
www.txt.ir
:
} int n[5] = {32 , 27 , 64 , 18 , 95
n .
:
} int n[] = { 1 , 2 , 3 , 4 , 5
5 n .
:
}int num[10] = {0
10 num .
:
}int num[10] = {1
110
www.txt.ir
www.txt.ir
1
.
.
.
:
=
const
:
;arraySize = 10
int
const
10 arraySize .
. .
" "
.
:
>#include <iostream.h
)(void main
{
;const int x = 7
" cout << "The value of constant variable x is:
;<< x << endl
}
111
www.txt.ir
www.softgozar.com
www.txt.ir
7 x cout .
.
>#include <iostream.h
)(void main
{
;const int x
;x=7
}
.
Compiling C:\TCP\BIN\CONST1.CPP:
Error : Constant variable 'x' must be initialized
Error : Cannot modify a const object
: for
for .
>#include <iostream.h
)(void main
{
;const int arraySize = 10
;] int s[ arraySize
) for ( int i = 0; i < arraySize; i++
;s[ i ] = 2 + 2 * i
;cout << "Element Value" << endl
) for ( int j = 0; j < arraySize; j++
112
www.txt.ir
www.txt.ir
:
Value
2
4
6
8
10
12
14
16
18
20
Element
0
1
2
3
4
5
6
7
8
9
: 10
.
>#include <iostream.h
)(void main
{
;const int arraySize = 10
;int total = 0,i
;] int a[ arraySize
)for (i = 0; i < arraySize; i++
{
;" cout << "Enter number " << i << " :
;] cin >> a[ i
}
) for (i = 0; i < arraySize; i++
113
www.txt.ir
www.txt.ir
total += a[ i ];
cout << "Total of array element values is "
<< total << endl;
}
:
Enter
Enter
Enter
Enter
Enter
Enter
Enter
Enter
Enter
Enter
Total
number 0
number 1
number 2
number 3
number 4
number 5
number 6
number 7
number 8
number 9
of array
: 12
: 3
: 4
: 654
: 34
: 2
: 123
: 794
: 365
: 23
element values is 2014
11 9 13 5 17 1} :
. { 19 3 15 7
#include <iostream.h>
int main()
{
const int arraySize = 10;
int n[ arraySize ] = { 19, 3, 15, 7, 11,
9, 13, 5, 17, 1 };
cout << "Element" << " Value" << endl;
for ( int i = 0; i < arraySize; i++ ) {
cout << i << "\t " << n[ i ] << "\t";
for ( int j = 0; j < n[ i ]; j++ )
cout << '*';
114
www.txt.ir
www.txt.ir
Element
0
1
2
3
4
5
6
7
8
9
Value
19
3
15
7
11
9
13
5
17
1
*******************
***
***************
*******
***********
*********
*************
*****
*****************
*
6000 :
( ) .
#include <iostream.h>
#include <stdlib.h>
#include <time.h>
void main()
{
const int arraySize = 7;
int frequency[ arraySize ] = { 0 };
srand( time( 0 ) );
for ( int roll = 1; roll <= 6000; roll++ )
++frequency[ 1 + rand() % 6 ];
115
www.txt.ir
www.txt.ir
Frequency
1023
990
1008
971
1025
983
Face
1
2
3
4
5
6
;] ++frequency [rand()%6 + 1
rand()%6 + 1 1 6
.
.
).
(
"hello" : .
;"char string1[]="hello
string1 hello .
hello 5
116
www.txt.ir
www.txt.ir
. string1 6 . C++
' '\0 . .
}'char string1[]={'h','e','l','l','o','\0
string1 .
)'( ' '\0 .
;" char string1[]="hello .
. ]string1[0
' 'h ] string1[3 ' 'l ] string1[5 ' '\0 .
cin
.
;]char string2[20
19
.
;cin >> string2
string2
. cin
.
; cin >> string2 " "hello there hello
string2 . .
.
117
www.txt.ir
www.txt.ir
>#include <iostream.h
)(void main
{
;] char name[ 20
;" cout << "Please Enter your name :
;cin >> name
cout << "Welcome, " << name
; "<< " to this program. \n
;"cout << "Your separated name is\n
) for ( int i = 0; name[ i ] != '\0'; i++
;' ' << ] cout << name[ i
}
for .
' name[ i ] != '\0
.
static . static
.
.
118
www.txt.ir
www.txt.ir
#include <iostream.h>
void staticArrayInit( void );
void automaticArrayInit( void );
int main()
{
cout << "First call to each function:\n";
staticArrayInit();
automaticArrayInit();
cout << "\n\nSecond call to each function:\n";
staticArrayInit();
automaticArrayInit();
cout << endl;
return 0;
}
// function to demonstrate a static local array
void staticArrayInit( void )
{
// initializes elements to 0
// first time function is called
static int array1[ 3 ]={0};
cout << "\nValues on entering staticArrayInit:\n";
// output contents of array1
for ( int i = 0; i < 3; i++ )
cout << "array1[" << i << "] = "
<< array1[ i ] << " ";
cout << "\nValues on exiting staticArrayInit:\n";
// modify and output
for ( int j = 0; j <
cout << "array1["
<< ( array1[
contents of array1
3; j++ )
<< j << "] = "
j ] += 5 ) << " ";
119
www.txt.ir
www.txt.ir
entering staticArrayInit:
= 0 array1[1] = 0 array1[2] = 0
exiting staticArrayInit:
= 5 array1[1] = 5 array1[2] = 5
Values on
array2[0]
Values on
array2[0]
entering automaticArrayInit:
= 1 array2[1] = 2 array2[2] = 3
exiting automaticArrayInit:
= 6 array2[1] = 7 array2[2] = 8
120
www.txt.ir
www.txt.ir
entering staticArrayInit:
= 5 array1[1] = 5 array1[2] = 5
exiting staticArrayInit:
= 10 array1[1] = 10 array1[2] = 10
Values on
]array1[0
Values on
]array1[0
entering automaticArrayInit:
= 1 array2[1] = 2 array2[2] = 3
exiting automaticArrayInit:
= 6 array2[1] = 7 array2[2] = 8
Values on
]array2[0
Values on
]array2[0
array1 staticArrayInit
.
array2 automaticArrayInit
.
)][(
. x :
;]int x[24
modifyArray :
;)modifyArray(x,24
. modifyArray .
.
121
www.txt.ir
www.txt.ir
C++
.
.
.
:
.
. .
. modifyArray
:
)void modifyArray (int b[] ,int array size
modifyArray
b arraySize .
)][(
. :
;)void modifyArray (int [] , int
.
>#include <iostream.h
;) void modifyArray( int [], int
122
www.txt.ir
www.txt.ir
123
www.txt.ir
www.txt.ir
:
Effects of passing entire array by reference:
4
8
modifyArray a
. modifyElement
.
. const
124
www.txt.ir
www.txt.ir
.
:
#include <iostream.h>
void tryToModifyArray( const int [] );
void main()
{
int a[] = { 10, 20, 30 };
tryToModifyArray( a );
cout << a[0] <<' '<< a[1] <<' '<< a[2] <<'\n';
}
// In function tryToModifyArray, "b" cannot be used
// to modify the original array "a" in main.
void tryToModifyArray( const int b[] )
{
b[ 0 ] /= 2; // error
b[ 1 ] /= 2; // error
b[ 2 ] /= 2; // error
}
.
Error in line 19: Cannot modify a const object
Error in line 20: Cannot modify a const object
125
www.txt.ir
www.txt.ir
.
.
:
2,5,4,3,6,1
:
;}int a[] = { 2 , 5 , 4 , 3 , 6 , 1
a .
.
.
.
.
>#include <iostream.h
;)void showArray(const int [] , int
)(void main
{
;const int arraySize = 6
;}int a[ arraySize ] = { 2, 5, 4, 3, 6 ,1
;int hold
;"cout << "Data items in original order\n
;)showArray(a,arraySize
) for ( int i = 0; i < arraySize - 1 ; i++
126
www.txt.ir
www.txt.ir
:
Data items in original order
2 5 4 3 6 1
Data items in ascending order
1 2 3 4 5 6
. showArray
j . i = 0
.
127
www.txt.ir
www.txt.ir
. i = 1
.
.
. .
.
128
www.txt.ir
www.txt.ir
.
.
:
>#include <iostream.h
;) int linearSearch(const int [], int, int
)(void main
{
;const int arraySize = 7
;}int a[ arraySize ]={2,6,4,3,12,10,5
;int searchKey
;" cout << "Enter integer search key:
;cin >> searchKey
;)int element=linearSearch(a, searchKey, arraySize
) if ( element != -1
" cout << "Found value in element
;<< element << endl
else
;cout << "Value not found" << endl
}
int linearSearch( const int array[],
) int key, int sizeOfArray
{
) for ( int j = 0; j < sizeOfArray; j++
) if ( array[ j ] == key
;return j
;return -1
129
www.txt.ir
www.txt.ir
:
Enter integer search key: 12
Found value in element 4
12 :
20 .
.
Enter integer search key: 20
Value not found
20 :
130
www.txt.ir
www.txt.ir
. .
.
.
.
. )
( )
( .
.
>#include <iostream.h
;)int binarySearch( const int [], int, int
)(void main
{
;const int arraySize = 15
int a[ arraySize ]={0,2,4,6,8,10,12,14,
;}16,18,20,22,24,26,28
;int key
;" cout << "Enter a number between 0 and 28:
;cin >> key
= int result
;)binarySearch( a, arraySize, key
) if ( result != -1
" cout << '\n' << key << " found in array element
;<< result << endl
131
www.txt.ir
www.txt.ir
else
cout << '\n' << key << " not found" << endl;
}
int binarySearch( const int b[],
int arraySize ,
int searchKey )
{
int middle,low=0,high=arraySize - 1;
while ( low <= high )
{
middle = ( low + high ) / 2;
if ( searchKey < b[ middle ] )
high = middle - 1;
else
if ( searchKey > b[ middle ] )
low = middle + 1;
else return middle;
}
return -1;
}
:
Enter a number between 0 and 28: 8
8 found in array element 4
: 8
132
www.txt.ir
www.txt.ir
25 . :
Enter a number between 0 and 28: 25
25 not found
25 :
C++ .
.
. :
;]int a[3][4
133
www.txt.ir
www.txt.ir
3 4 :
] a[i][j i j
.
:
;}}int b[2][2] = {{1,2},{3,4
b :
1
3
2
4
2 3 :
>#include <iostream.h
;) ] void printArray( int [][ 3
)(void main
{
;} } int array1[ 2 ][ 3 ] = { { 1, 2, 3 }, { 4, 5, 6
;} int array2[ 2 ][ 3 ] = { 1, 2, 3, 4, 5
;} } int array3[ 2 ][ 3 ] = { { 1, 2 }, { 4
;cout << "Values in array1 by row are:" << endl
;) printArray( array1
134
www.txt.ir
www.txt.ir
:
Values in array1 by row are:
1 2 3
4 5 6
Values in array2 by row are:
1 2 3
4 5 0
Values in array3 by row are:
1 2 0
4 0 0
PrintArray .
] int a[][3 .
.
135
www.txt.ir
www.txt.ir
: 2 10 10
.
>#include <iostream.h
) (void main
{
;int a[10][10],i,j
)for (i=0;i<10;i++
)for (j=0;j<10;j++
;)a[i][j]=(i+1)*(j+1
{)for (i=0;i<10;i++
)for (j=0;j<10;j++
;"cout <<a[i][j]<<"\t
;cout<<endl
}
}
:
10
20
18
16
14
12
10
30
27
24
21
18
15
12
40
36
32
28
24
20
16
12
50
45
40
35
30
25
20
15
10
60
54
48
42
36
30
24
18
12
70
63
56
49
42
35
28
21
14
80
72
64
56
48
40
32
24
16
136
www.txt.ir
www.txt.ir
90
81
72
63
54
45
36
27
18
.
.
. :
count 7 .
countPtr 7 .
.
count int countPtr int
.
; int count , *countPtr
* .
:
137
www.txt.ir
www.txt.ir
)&( .
;int y=5
;int *yPtr
;yPtr = &y
y int 5 yPtr
int y yPtr .
yPtr y .
:
>#include <iostream.h
)( void main
138
www.txt.ir
www.txt.ir
{
int x = 5, y = 15;
int *xPtr, *yPtr;
xPtr = &x;
yPtr = &y;
cout << "The value of x is " << x
<< "\nThe address of x is " << &x
<< "\nThe value of xPtr is " << xPtr;
cout << "\n\nThe value of y is " << y
<< "\nThe address of y is " << &y
<< "\nThe value of yPtr is " << yPtr;
*xPtr = 10;
cout << "\n\nx=" << x << " and y=" << y;
*yPtr = *xPtr;
cout << "\nx=" << x << " and y=" << y;
xPtr = yPtr;
cout << "\nx=" << x << " and y=" << y;
*xPtr = 20;
cout << "\nx=" << x << " and y=" << y;
}
:
The value of x is 5
The address of x is 0x8fb4fff4
The value of xPtr is 0x8fb4fff4
The value of y is 15
The address of y is 0x8fb4fff2
The value of yPtr is 0x8fb4fff2
x=10 and y=15
x=10 and y=10
x=10 and y=10
139
www.txt.ir
www.txt.ir
x y x 5 y 15
xPtr yPtr .
;xPtr = &x
;yPtr = &y
x xPtr
y yPtr .
; *xPtr = 10 xPtr ) ( x 10
; *yPtr = *xPtr xPtr
yPtr x y
.
; xPtr = yPtr yPtr y xPtr
xPtr x y
; *xPtr = 20 x 20
y 20 .
. .
.
.
.
>#include <iostream.h
140
www.txt.ir
www.txt.ir
:
The original value of number is 5
The new value of number is 125
*
* .
&
.
141
www.txt.ir
www.txt.ir
const
const
const .
.
. :
void f( const int * ); // prototype
)(int main
{
;int y
f( &y ); // f attempts illegal modification
;return 0
}
// xPtr cannot modify the value of the variable
// to which it points
) void f( const int *xPtr
{
*xPtr = 100; // error: cannot modify a const object
}
.
Compiling CONSTP1.CPP:
Error CONSTP1.CPP 16: Cannot modify a const object
const int *xptr .
.
142
www.txt.ir
www.txt.ir
const
.
. :
)(int main
{
;int x, y
// ptr is a constant pointer to an integer that can
// be modified through ptr, but ptr always points
// to the same memory location.
;int * const ptr = &x
*ptr = 7; // allowed: *ptr is not const
;ptr = &y; // error: ptr is const
//
cannot assign new address
;return 0
}
.
Compiling CONSTP2.CPP:
Error CONSTP2.CPP 11: Cannot modify a const object
143
www.txt.ir
www.softgozar.com
www.txt.ir
const .
. :
>#include <iostream.h
)(int main
{
;int x = 5, y
// ptr is a constant pointer to a constant integer.
;// ptr always points to the same location
// the integer at that location cannot be modified.
;const int *const ptr = &x
;cout << *ptr << endl
;*ptr = 7; // error: *ptr is const
//
cannot assign new value
;ptr = &y; // error: ptr is const
//
cannot assign new address
;return 0
}
.
Compiling CONSTP3.CPP:
Error CONSTP3.CPP 14: Cannot modify a const object
Error CONSTP3.CPP 16: Cannot modify a const object
144
www.txt.ir
www.txt.ir
.
.
) (++ ) (-- . )=+
(+ )= - (- .
] int v[5 3000
vptr ] v[0 .
vptr v :
;vptr = v
;]vptr = &v[0
3000+2 3002
.
. ; vptr += 2 (3000
+ 2*4) 3008 int
. v vptr ] v[2 .
int ; vptr += 2
(3000 + 2*2)3004 .
vptr ] v[4 3016 :
;vptr -= 4
145
www.txt.ir
www.txt.ir
v .
;--vptr
;vptr--
.
vptr ) 3000 ] v[0 ( v2ptr ) 3008
] v[2 ( :
;x=v2ptr - vptr
vptr v2ptr x x 2 .
.
.
C++
. :
146
www.txt.ir
www.txt.ir
;]int b[5
;int bptr
) (
bptr b :
;bptr = b
bptr b :
]bptr = &b[0
] b[3 bptr b
:
)*(bptr + 3
bptr+3 . bptr
] b[0 bptr+3
]b[3
) *(bptr + 3 ] b[3 .
* + .
*bptr+3 3 ] b[0 .
) ) *(b + 3 b
( ] b[3
.
] bptr[1 ]b[1
bptr b .
147
www.txt.ir
www.txt.ir
: ; b+=3
b
.
:
>#include <iostream.h
)(void main
{
;} int b[] = { 10, 20, 30, 40
;int *bPtr = b
;int i
;"cout << "b[i]:\n
) for ( i = 0; i < 4; i++
;'cout << "b[" << i << "] = " << b[ i ] << '\n
;"i):\n
) 4; i++
" = )" << " << i
;'i ) << '\n
+
<
+
+
148
www.txt.ir
www.txt.ir
10
20
30
40
10
20
30
40
i):
= )0
= )1
= )2
= )3
10
20
30
40
10
20
30
40
i):
= )0
= )1
= )2
= )3
b[i]:
= ]b[0
= ]b[1
= ]b[2
= ]b[3
+
+
+
+
+
*(b
*(b
*(b
*(b
*(b
bPtr[i]:
= ]bPtr[0
= ]bPtr[1
= ]bPtr[2
= ]bPtr[3
+
+
+
+
+
*(bPtr
*(bPtr
*(bPtr
*(bPtr
*(bPtr
.
.
. :
= ]const char *s[4
} "{ "string1","string2","string3","string4
char* .
s char .
149
www.txt.ir
www.txt.ir
. C++
.
: char
.
. :
150
www.txt.ir
www.txt.ir
.
.
.
.
. bubble swap ascending descending .
bubble
.
ascending descending
.
.
1 ascending
bubble .
2 descending
bubble .
:
>#include <iostream.h
;) ) void bubble( int [], const int, int (*)( int, int
;) void swap( int * const, int * const
;) int ascending( int, int
;) int descending( int, int
)(void main
{
;const int arraySize = 10
;int order
151
www.txt.ir
www.txt.ir
int counter;
int a[ arraySize ] = { 2, 6, 4, 8, 10,
12, 89, 68, 45, 37 };
cout << "Enter 1 to sort in ascending order,\n"
<< "Enter 2 to sort in descending order: ";
cin >> order;
cout << "\nData items in original order\n";
for ( counter = 0; counter < arraySize; counter++ )
cout << " " << a[ counter ];
if ( order == 1 ) {
bubble( a, arraySize,
cout << "\nData items
}
else {
bubble( a, arraySize,
cout << "\nData items
}
ascending );
in ascending order\n";
descending );
in descending order\n";
152
www.txt.ir
www.txt.ir
:
Enter 1 to sort in ascending order,
Enter 2 to sort in descending order: 1
Data items
2 6 4
Data items
2 4 6
Enter 1 to
Enter 2 to
in original order
8 10 12 89 68 45 37
in ascending order
8 10 12 37 45 68 89
sort in ascending order,
sort in descending order: 2
Data items in
2 6 4 8
Data items in
89 68 45
original order
10 12 89 68 45 37
descending order
37 12 10 8 6 4 2
: bubble
int (*compare) (int , int)
bubble
. int
153
www.txt.ir
www.txt.ir
*compare compare
. *compare
:
)int *compare (int,int
int .
bubble :
)int (*)(int,int
.
bubble :
)](*compare) (work[count],work[count+1
.
.
.
.
.
.
:
>#include <iostream.h
;) void function1( int
154
www.txt.ir
www.txt.ir
155
www.txt.ir
www.txt.ir
:
Enter a number between 0 and 2, 3 to end: 2
You entered 2 so function3 was called
Enter a number between 0 and 2, 3 to end: 0
You entered 0 so function1 was called
Enter a number between 0 and 2, 3 to end: 1
You entered 1 so function2 was called
Enter a number between 0 and 2, 3 to end: 3
Program execution completed.
. 0 2
f . :
;)(*f[choice]) (choice
f choice .
string.h
.
156
www.txt.ir
www.txt.ir
s1 s1 s2
.
char *strncpy (char *s1, const char *s2, size_t n);
s1 s1 s2 n
: .
#include <iostream.h>
#include <string.h>
void main()
{
char x[] = "Happy Birthday to You";
char y[ 25 ];
char z[ 15 ];
strcpy( y, x ); // copy contents of x into y
cout << "The string in array x is: " << x
<< "\nThe string in array y is: " << y << '\n';
// copy first 14 characters of x into z
strncpy( z, x, 14 ); // does not copy null character
z[ 14 ] = '\0'; // append '\0' to z's contents
cout << "The string in array z is: " << z << endl;
}
:
The string in array x is: Happy Birthday to You
The string in array y is: Happy Birthday to You
The string in array z is: Happy Birthday
157
www.txt.ir
www.txt.ir
. s1 s1 s2
char *strncat (char *s1, const char *s2, size_t n);
s1 s1 s2 n
: .
#include <iostream.h>
#include <string.h>
void main()
{
char s1[ 20 ] = "Happy ";
char s2[] = "New Year ";
char s3[ 40 ] = "";
cout << "s1 = " << s1 << "\ns2 = " << s2;
strcat( s1, s2 ); // concatenate s2 to s1
cout << "\n\nAfter strcat(s1, s2):\ns1 = " << s1
<< "\ns2 = " << s2;
// concatenate first 6 characters of s1 to s3
// and places '\0' after last character
strncat( s3, s1, 6 );
:
158
www.txt.ir
www.txt.ir
s1 = Happy
s2 = New Year
After strcat(s1, s2):
s1 = Happy New Year
s2 = New Year
After strncat(s3, s1, 6):
s1 = Happy New Year
s3 = Happy
After strcat(s3, s1):
s1 = Happy New Year
s3 = Happy Happy New Year
. s2 s1
s2 s1 s2 s1
.
int strncmp (const char *s1, const char *s2, size_t n);
s2 s1 n
: . strcmp
#include <iostream.h>
#include <string.h>
void main()
{
char *s1 = "Happy New Year";
char *s2 = "Happy New Year";
char *s3 = "Happy Holidays";
159
www.txt.ir
www.txt.ir
cout <<
<<
<<
<<
<<
<<
cout <<
<<
<<
<<
<<
:
s1 = Happy New Year
s2 = Happy New Year
s3 = Happy Holidays
strcmp(s1, s2) = 0
strcmp(s1, s3) = 6
strcmp(s3, s1) = -6
strncmp(s1, s3, 6) = 0
strncmp(s1, s3, 7) = 6
strncmp(s3, s1, 7) = -6
: . s2 s1
#include <iostream.h>
#include <string.h>
void main()
{
char sentence[] ="This is a sentence with 7 tokens";
160
www.txt.ir
www.txt.ir
char *tokenPtr;
cout << "The string to be tokenized is:\n"<<sentence
<< "\n\nThe tokens are:\n\n";
tokenPtr = strtok( sentence, " " );
while ( tokenPtr != NULL ) {
cout << tokenPtr << '\n';
tokenPtr = strtok( NULL, " " ); // get next token
}
cout <<"\nAfter strtok, sentence ="<<sentence<<endl;
}
:
The string to be tokenized is:
This is a sentence with 7 tokens
The tokens are:
This
is
a
sentence
with
7
tokens
After strtok, sentence = This
: . s
#include <iostream.h>
#include <string.h>
161
www.txt.ir
www.txt.ir
void
{
char
char
char
main()
*string1 = "abcdefghijklmnopqrstuvwxyz";
*string2 = "four";
*string3 = "Boston";
cout <<
<<
<<
<<
<<
<<
}
:
The length of "abcdefghijklmnopqrstuvwxyz" is 26
The length of "four" is 4
The length of "Boston" is 6
)(
.
:
struct Time {
int hour;
int minute;
int second;
};
Time struct
) minute ( ) hour Time
162
www.txt.ir
www.txt.ir
( ) second ( .
.
Time
. :
;Time timeObject
;]Time timeArray[10
;Time *timePtr=&timeObject
) (. )> (- .
:
;timeObject.hour = 13
;timeObject.minute = 33
;timeObject.second = 20
163
www.txt.ir
www.txt.ir
Time
dinnerTime Time
printUniversal printStandard .
>#include <iostream.h
{ struct Time
)int hour; // 0-23 (24-hour clock format
int minute; // 0-59
int second; // 0-59
;}
;) & void printUniversal( const Time
;) & void printStandard( const Time
)(int main
{
;Time dinnerTime
;dinnerTime.hour = 18
164
www.txt.ir
www.txt.ir
dinnerTime.minute = 30;
dinnerTime.second = 0;
cout << "Dinner will be held at ";
printUniversal( dinnerTime );
cout << " universal time,\nwhich is ";
printStandard( dinnerTime );
cout << " standard time.\n";
dinnerTime.hour= 29; //set hour to invalid value
dinnerTime.minute= 73; //set minute to invalid value
cout << "\nTime with invalid values: ";
printUniversal( dinnerTime );
cout << endl;
return 0;
}
void printUniversal( const Time &t )
{
cout << (t.hour<10 ? "0":"") << t.hour << ":"
<< (t.minute<10 ? "0":"") << t.minute << ":"
<< (t.second<10 ? "0":"") << t.second;
}
:
Dinner will be held at 18:30:00 universal time,
which is 6:30:00 PM standard time.
165
www.txt.ir
www.txt.ir
Time
. .
) (
) ( .
.
class . :
{ class Time
public:
;)(Time
;) void setTime( int, int, int
;)(void printUniversal
;)(void printStandard
private:
;int hour
;int minute
;int second
;}
Time class }{
);( . Time
Time hourminute
second .
public: private: ) ( .
public private
Time .
private
166
www.txt.ir
www.txt.ir
.
) (: .
) ( public . Time
setTime ,Time , printUniversal printStandard
Time publice
.
. .
.
.
Time Time
. :
;Time sunset
;]Time arrayofTime [5
;Time *timeptr = & sunset
www.txt.ir
www.txt.ir
.
t setTime
. setTime
#include <iostream.h>
class Time {
public:
Time();
void setTime( int, int, int );
void printUniversal();
void printStandard();
private:
int hour; // 0 - 23 (24-hour clock format)
int minute; // 0 - 59
int second; // 0 - 59
}
Time::Time()
{
hour = minute = second = 0;
}
void Time::setTime( int h, int m,
{
hour = ( h >= 0 && h < 24 ) ? h
minute = ( m >= 0 && m < 60 ) ?
second = ( s >= 0 && s < 60 ) ?
}
int s )
: 0;
m : 0;
s : 0;
void Time::printUniversal()
{
cout << (hour<10 ? "0":"") << hour << ":"
<< (minute<10 ? "0":"") << minute << ":"
<< (second<10 ? "0":"") << second;
}
void Time::printStandard()
{
168
www.txt.ir
www.txt.ir
:
The initial universal time is 00:00:00
The initial standard time is 12:00:00 AM
169
www.txt.ir
www.txt.ir
.
) (:: :
)(void Time::printUniversal
{
"cout << (hour<10 ? "0":"") << hour << ":
"<< (minute<10 ? "0":"") << minute << ":
;<< (second<10 ? "0":"") << second
}
) ( )
(
.
.
) (. )> (- .
.
) (. )> (-
.
170
www.txt.ir
www.txt.ir
.
.
.
) (::
.
Count int x
print . Count
counter ) countPtr ( Count
countPtr counter . x
.
.
:
>#include <iostream.h
{ class Count
public:
;int x
)(void print
{
;cout << x << endl
}
;}
)(void main
{
171
www.txt.ir
www.txt.ir
;Count counter
;Count *counterPtr = &counter
" cout << "Assign 1 to x and print
;" << "using the object's name:
;counter.x = 1
;)(counter.print
;" cout << "Assign 3 to x and print using a pointer:
;counterPtr->x = 3
;)(counterPtr->print
}
:
Assign 1 to x and print using the object's name: 1
Assign 3 to x and print using a pointer: 3
public private
.
private
.
.
public private
.
.
:
>#include <iostream.h
172
www.txt.ir
www.txt.ir
class Time {
public:
Time();
void setTime( int, int, int );
void printUniversal();
void printStandard();
private:
int hour; // 0 - 23 (24-hour clock format)
int minute; // 0 - 59
int second; // 0 - 59
}
Time::Time()
{
hour = minute = second = 0;
}
void Time::setTime( int h, int m,
{
hour = ( h >= 0 && h < 24 ) ? h
minute = ( m >= 0 && m < 60 ) ?
second = ( s >= 0 && s < 60 ) ?
}
int s )
: 0;
m : 0;
s : 0;
void Time::printUniversal()
{
cout << (hour<10 ? "0":"") << hour << ":"
<< (minute<10 ? "0":"") << minute << ":"
<< (second<10 ? "0":"") << second;
}
void Time::printStandard()
{
cout << ( ( hour == 0 || hour == 12 ) ?
12 : hour % 12 ) << ":"
<< (minute<10 ? "0":"") << minute << ":"
<< (second<10 ? "0":"") << second
<< (hour < 12 ? " AM" : " PM" );
}
int main()
173
www.txt.ir
www.txt.ir
{
Time t; // create Time object
t.hour = 7; // error: 'Time::hour' is not accessible
// error: 'Time::minute' is not accessible
;cout << "minute = " << t.minute
;return 0
}
.
Error in line 50: 'Time::hour' is not accessible
Error in line 53: 'Time::minute' is not accessible
.
.
. .
hour minute second
.
.
.
.
. :
174
www.txt.ir
www.txt.ir
#include <iostream.h>
class CRectangle {
int width, height;
public:
CRectangle (int,int);
int area (void) {return (width*height);}
};
CRectangle::CRectangle (int a, int b) {
width = a;
height = b;
}
int main () {
CRectangle rect (3,4);
CRectangle rectb (5,6);
cout << "rect area: " << rect.area() << endl;
cout << "rectb area: " << rectb.area() << endl;
}
:
rect area: 12
rectb area: 30
: .
#include <iostream.h>
class CRectangle {
int width, height;
public:
CRectangle ();
CRectangle (int,int);
int area (void) {return (width*height);}
};
CRectangle::CRectangle () {
175
www.txt.ir
www.txt.ir
;width = 5
;height = 5
}
{ )CRectangle::CRectangle (int a, int b
;width = a
;height = b
}
{ )( int main
;)CRectangle rect (3,4
;CRectangle rectb
;cout << "rect area: " << rect.area() << endl
;cout << "rectb area: " << rectb.area() << endl
}
:
rect area: 12
rectb area: 25
.
time .
.
.
>#include <iostream.h
{ class Time
public:
;)Time( int = 0, int = 0, int = 0
;) void setTime( int, int, int
;)(void printUniversal
;)(void printStandard
private:
)int hour; // 0 - 23 (24-hour clock format
176
www.txt.ir
www.txt.ir
int minute; // 0 - 59
int second; // 0 - 59
}
Time::Time( int hr, int min, int sec )
{
setTime( hr, min, sec );
}
void Time::setTime( int h, int m,
{
hour = ( h >= 0 && h < 24 ) ? h
minute = ( m >= 0 && m < 60 ) ?
second = ( s >= 0 && s < 60 ) ?
}
int s )
: 0;
m : 0;
s : 0;
void Time::printUniversal()
{
cout << (hour<10 ? "0":"") << hour << ":"
<< (minute<10 ? "0":"") << minute << ":"
<< (second<10 ? "0":"") << second;
}
void Time::printStandard()
{
cout << ( ( hour == 0 || hour == 12 ) ?
12 : hour % 12 ) << ":"
<< (minute<10 ? "0":"") << minute << ":"
<< (second<10 ? "0":"") << second
<< (hour < 12 ? " AM" : " PM" );
}
void main()
{
Time t1;
//
Time t2( 2 );
//
Time t3( 21, 34 );
//
Time t4( 12, 25, 42 ); //
Time t5( 27, 74, 99 ); //
177
www.txt.ir
www.txt.ir
:
Constructed with:
all default arguments:
00:00:00
12:00:00 AM
hour specified; default minute and second:
02:00:00
2:00:00 AM
178
www.txt.ir
www.txt.ir
Time t1
t2 t3 t4
t5 .
setTime
hour minute
second .
)~(
.
)
( .
.
.
. .
:
179
www.txt.ir
www.txt.ir
class CreateAndDestroy {
public:
CreateAndDestroy();
~CreateAndDestroy();
private:
int objectID;
};
CreateAndDestroy::CreateAndDestroy(int objectNumber)
{
objectID = objectNumber;
cout << "Object "<<objectID<<" constructor runs\n";
}
CreateAndDestroy::~CreateAndDestroy()
{
cout << "Object "<<objectID<<" destructor runs\n";
}
.
: .
#include <iostream.h>
class CreateAndDestroy {
public:
CreateAndDestroy( int, char * );
~CreateAndDestroy();
private:
int objectID;
char *message;
};
CreateAndDestroy::CreateAndDestroy(
180
www.txt.ir
www.txt.ir
181
www.txt.ir
www.txt.ir
:
Object 1
destructor runs
const
. const .
const Time noon(12, 0, 0);
182
www.txt.ir
www.txt.ir
Time noon 12
.
C++
const . const
const
.
int Time::getHour() const
{
;return hour
}
getHour Time .
:
.1
.
.2
.
.3
.
.4 .
.
.5
const
.
.6 .
183
www.txt.ir
www.txt.ir
. Time
printStandard setHour
. 2
:
#include <iostream.h>
class Time {
public:
Time( int = 0, int = 0, int = 0);
void setTime( int, int, int );
void setHour( int );
void setMinute( int );
void setSecond( int );
int getHour() const;
int getMinute() const;
int getSecond() const;
void printUniversal() const;
void printStandard();
private:
int hour; // 0 - 23 (24-hour clock format)
int minute; // 0 - 59
int second; // 0 - 59
}
Time::Time( int hour, int minute, int second )
{
setTime( hour, minute, second );
}
void Time::setTime( int hour, int minute, int second )
{
setHour( hour );
setMinute( minute );
setSecond( second );
}
184
www.txt.ir
www.txt.ir
185
www.txt.ir
www.txt.ir
// non-constant object
// constant object
wakeUp.setHour( 18 );
// OBJECT
// non-const
MEMBER FUNCTION
non-const
noon.setHour( 12 );
// const
non-const
wakeUp.getHour();
// non-const
const
noon.getMinute();
noon.printUniversal();
// const
// const
const
const
noon.printStandard();
// const
non-const
return 0;
}
:
Warning W8037 100: Non-const function
Time::setHour(int)
called for const object in function main()
Warning W8037 107: Non-const function
Time::printStandard()
called for const object in function main()
*** 2 errors in Compile ***
:
) ( AlarmClock
. Time
186
www.txt.ir
www.txt.ir
.
.
.
.
:
#include <iostream.h>
#include <string.h>
class Date {
public:
Date( int = 1, int = 1, int = 1900 );
void print() const;
~Date();
private:
int month; // 1-12 (January-December)
int day; // 1-31 based on month
int year; // any year
int checkDay( int ) const;
};
Date::Date(
{
if ( mn >
month =
else {
month =
cout <<
<<
}
year = yr;
day = checkDay( dy );
cout << "Date object constructor for date ";
print();
187
www.txt.ir
www.txt.ir
188
www.txt.ir
www.txt.ir
~Employee();
private:
char firstName[ 25 ];
char lastName[ 25 ];
const Date birthDate; //composition: member object
const Date hireDate; //composition: member object
};
189
www.txt.ir
www.txt.ir
int main()
{
Date birth( 7, 24, 1949 );
Date hire( 3, 12, 1988 );
Employee manager( "Bob", "Jones", birth, hire );
cout << '\n';
manager.print();
cout << "\nTest Date constructor "
<<"with invalid values:\n";
Date lastDayOff(14,35,1994); //invalid month and day
cout << endl;
return 0;
}
:
Date object constructor for date 7/24/1949
Date object constructor for date 3/12/1988
Employee object constructor: Bob Jones
Jones, Bob
Hired: 3/12/1988 Birth date: 7/24/1949
Test Date constructor with invalid values:
Month 14 invalid. Set to month 1.
Day 35 invalid. Set to day 1.
Date object constructor for date 1/1/1994
Date object destructor for date 1/1/1994
Employee object destructor: Jones, Bob
Date object destructor for date 3/12/1988
Date object destructor for date 7/24/1949
Date object destructor for date 3/12/1988
Date object destructor for date 7/24/1949
190
www.txt.ir
www.txt.ir
) ( :
Employee Date .
.
: print Date
. C++ . print
.
. ) (
191
www.txt.ir
www.txt.ir
.
friend .
{class Count
;)friend void setX(Count & , int
;int x
}
setX Count .
classTwo classOne
. classOne :
;friend class classTwo
setX Count
x Count .
.
>#include <iostream.h
{ class Count
;) friend void setX( Count &, int
public:
Count(): x( 0 ) // initialize x to 0
{
// empty body
}
void print() const
{
;cout << x << endl
}
private:
;int x
;}
192
www.txt.ir
www.txt.ir
:
counter.x after instantiation: 0
counter.x after call to setX friend function: 8
Count .
x 0 .
) Count(): x( 0
this
C++ this . this
.
. :
193
www.txt.ir
www.txt.ir
>#include <iostream.h
{ class CDummy
public:
;)int isitme (CDummy& param
;}
)int CDummy::isitme (CDummy& param
{
;if (¶m == this) return 1
;else return 0
}
{ )( int main
;CDummy a
;CDummy* b = &a
) )if ( b->isitme(a
;"cout << "yes, &a is b
;return 0
}
:
yes, &a is b
c++
.
new delete . new.h .
> #include <new.h .
:
;Time *timePtr
;timePtr = new Time
194
www.txt.ir
www.txt.ir
new Time
new
. new ) double int (...
. new 0
.
delete :
;delete timePtr
timePtr
.
c++ .
:
;)double *ptr=new double(3.14159
double 3.14159
Ptr .
. :
;)Time *timePtr= new Time(12,0,0
Time 12
timePtr .
new .
10 :
;]int *gradesArray=new int[10
195
www.txt.ir
www.txt.ir
10
gradesArray .
:
;delete [] gradesArray
: ][
delete delete .
static
.
) (static .
.
.
public private .
.
) (:: .
:
>#include <iostream.h
>#include <new.h
>#include <string.h
{ class Employee
196
www.txt.ir
www.txt.ir
public:
Employee( const char *, const char * );
~Employee();
const char *getFirstName() const;
const char *getLastName() const;
// static member function
static int getCount();
private:
char *firstName;
char *lastName;
// static data member
static int count;
};
int Employee::count = 0;
int Employee::getCount()
{
return count;
}
// constructor dynamically allocates space for
// first and last name and uses strcpy to copy
// first and last names into the object
Employee::Employee(const char *first,const char *last)
{
firstName = new char[ strlen( first ) + 1 ];
strcpy( firstName, first );
lastName = new char[ strlen( last ) + 1 ];
strcpy( lastName, last );
++count; // increment static count of employees
cout << "Employee constructor for " << firstName
<< ' ' << lastName << " called." << endl;
}
// destructor deallocates dynamically allocated memory
Employee::~Employee()
197
www.txt.ir
www.txt.ir
{
cout << "~Employee() called for " << firstName
<< ' ' << lastName << endl;
delete [] firstName; // recapture memory
delete [] lastName; // recapture memory
--count; // decrement static count of employees
}
const char *Employee::getFirstName() const
{
return firstName;
}
const char *Employee::getLastName() const
{
return lastName;
}
int main()
{
cout <<"Number of employees before instantiation is "
<<Employee::getCount() << endl;
Employee *e1Ptr = new Employee( "Susan", "Baker" );
Employee *e2Ptr = new Employee( "Robert", "Jones" );
cout << "Number of employees after instantiation is "
<< e1Ptr->getCount();
cout <<
<<
<<
<<
<<
<<
"\n\nEmployee 1: "
e1Ptr->getFirstName()
" " << e1Ptr->getLastName()
"\nEmployee 2: "
e2Ptr->getFirstName()
" " << e2Ptr->getLastName() << "\n\n";
198
www.txt.ir
www.txt.ir
:
Number of employees before instantiation is 0
Employee constructor for Susan Baker called.
Employee constructor for Robert Jones called.
Number of employees after instantiation is 2
Employee 1: Susan Baker
Employee 2: Robert Jones
~Employee() called for Susan Baker
~Employee() called for Robert Jones
Number of employees after deletion is 0
getCount count
: Employee ( static)
int Employee::count = 0;
199
www.txt.ir
www.txt.ir
Employee
:
delete e1Ptr; //recapture memory
e1Ptr = 0; //disconnect pointer from free-store space
delete e2Ptr; //recapture memory
e2Ptr = 0; //disconnect pointer from free-store space
Employee
getCount count count
getCount :
)(Employee::getCount
.
.
. C++
C++
. . + -
C++ .
.
C++
.
200
www.txt.ir
www.txt.ir
.
. .
operator . +
operator+ . +
:
>#include <iostream.h
class CVector
{
public:
;) CVector (int =0 ,int =0
;)CVector operator+ (CVector
;)void showCVector(void
private:
;int x,y
;}
)CVector::CVector (int a, int b
{
;x = a
;y = b
}
)CVector CVector::operator+ (CVector vector
{
;CVector temp
;temp.x = x + vector.x
;temp.y = y + vector.y
;return temp
}
)void CVector::showCVector(void
{
;")" << cout << "("<< x << "," << y
}
201
www.txt.ir
www.txt.ir
)( int main
{
;)CVector a (3,1
;)CVector b (1,2
;CVector c
;c = a + b
;)(a.showCVector
;"cout << "+
;)(b.showCVector
;"=" << cout
;)(c.showCVector
;return 0
}
:
)(3,1)+(1,2)=(4,3
.
.
. C++
C++
. . + -
C++ .
.
C++
.
202
www.txt.ir
www.txt.ir
.
. .
operator . +
operator+ . +
:
>#include <iostream.h
class CVector
{
public:
;) CVector (int =0 ,int =0
;)CVector operator+ (CVector
;)void showCVector(void
private:
;int x,y
;}
)CVector::CVector (int a, int b
{
;x = a
;y = b
}
)CVector CVector::operator+ (CVector vector
{
;CVector temp
;temp.x = x + vector.x
;temp.y = y + vector.y
;return temp
}
)void CVector::showCVector(void
{
;")" << cout << "("<< x << "," << y
}
203
www.txt.ir
www.txt.ir
)( int main
{
;)CVector a (3,1
;)CVector b (1,2
;CVector c
;c = a + b
;)(a.showCVector
;"cout << "+
;)(b.showCVector
;"=" << cout
;)(c.showCVector
;return 0
}
:
)(3,1)+(1,2)=(4,3
C++ . :
][
)(
>-
++
--
&
*>-
<<
>>
<
>
=<
=>
==
=!
&&
||
=*
=/
=%
=+
=-
=<<
=>>
=&
=^
=|
204
www.txt.ir
www.txt.ir
new
][new
delete
][delete
:
.
*.
?:
::
sizeof
.
.
)( [] > -
.
.
) (private ) (friend
.
)
( ) (
.
. number
long int bigInteger1 HugeInteger
)
205
www.txt.ir
www.txt.ir
206
www.txt.ir
www.txt.ir
207
www.txt.ir
www.txt.ir
)(3,1)+(1,2)=(4,3
)(3,1)-(1,2)=(2,-1
<< >>
C++
<< >> .
.
. phoneNumber
. >>
<< .
:
>#include <iostream.h
{ class PhoneNumber
<<friend ostream &operator
;) & ( ostream&, const PhoneNumber
>>friend istream &operator
;) & ( istream&, PhoneNumber
private:
;] char areaCode[ 4
;] char exchange[ 4
;] char line[ 5
;}
<<ostream &operator
) ( ostream &output, const PhoneNumber &num
{
" " << output << num.areaCode
;<< num.exchange << " " << num.line
;// enables cout << a << b << c
;return output
}
>>istream &operator
208
www.txt.ir
www.txt.ir
:
Enter phone number in the form 123 456 7890:
021 224 5348
The phone number entered was: 021 224 5348
. << >>
cout ostream & <<
>> classObject>>cout
.classObject<<cin cin istream &
. .
209
www.txt.ir
www.txt.ir
>> operator :
;)operator>>(cin,phone
input cin
num phone .
exchange areacode line .
<< operator ostream output
phoneNumber num
ostream .
800 555 1212
phoneNumber .
:
;cout<<phone
<< operator :
210
www.txt.ir
www.txt.ir
;)operator<<(cout,phone
output cout
num phone .
exchange areacode line .
:
{ class
;() const oprerator
public:
...
}
:
{ class
oprerator
friend
;)& (const
...
}
211
www.txt.ir
www.txt.ir
{ class
public:
&oprerator const
;)& (const
...
}
:
{ class
&oprerator friend const
;)& &, const (
...
}
.
.
.
.
.
.
. :
;test::operator char* () const
212
www.txt.ir
www.txt.ir
. * char
test .
.
. s test
(char *) s
)(* s.operator char .
;myClass::operator int() const
;myClass::operator otherClass() const
myClass
myClass
otherClass .
++ --
C++ ++ -- .
:
)( operator++
//++x
{
...
}
) operator++(int x
//x++
{
...
}
)( operator--
//--x
{
...
213
www.txt.ir
www.txt.ir
}
) operator--(int x
//x--
{
...
}
:
//++x
//x++
//--x
//x--
214
www.txt.ir
www.softgozar.com
www.txt.ir