8/8/2019 Chapter02 Data Types Control Structures
1/76
2004 Trn Minh Chu. FOTECH. VNU Chng 2.
1
Ngn ng lp trnh C++Chng 2 Cc kiu d liu c bn
Cc cu trc iu khin
8/8/2019 Chapter02 Data Types Control Structures
2/76
2004 Trn Minh Chu. FOTECH. VNU Chng 2.
2
Ti liu c thm
Ti liu c thm cho chng ny: Section 2.1. Complete C++ Language Tutorial (CCLT)
Day 7. Teach Yourself C++ in 21 Days (TY21)
Namespace (Sec.5-2.CCLT) (Khng bt buc)
8/8/2019 Chapter02 Data Types Control Structures
3/76
2004 Trn Minh Chu. FOTECH. VNU Chng 2.
3
Chng 2 Kiu d liu v php ton c bnCu trc iu khin v cu trc chng trnh
mc
2.1 Cc kiu d liu c bn
2.2 Cc php gn tt, php tng, php gim
2.3 Cc php ton logic
2.4 Thut ton, m gi, iu khin ca chng trnh, s khi
2.5 S lc v cc cu trc iu khin
2.6 Cu trc la chn if, if/else
2.7 Php ton la chn 3 ngi2.8 Cu trc lpwhile
2.9 Thit lp thut ton
2.10 iu khin lp bng con m v gi tr canh
8/8/2019 Chapter02 Data Types Control Structures
4/76
2004 Trn Minh Chu. FOTECH. VNU Chng 2.
4
mc (tip theo)
2.11 Cc cu trc lng nhau
2.12 Vng lp for
2.13 Cu trc a la chn switch
2.14 Vng lp do/while
2.15 break v continue
2.16 S lc v lp trnh cu trc
Chng 2 Kiu d liu v php ton c bnCu trc iu khin v cu trc chng trnh
8/8/2019 Chapter02 Data Types Control Structures
5/76
2004 Trn Minh Chu. FOTECH. VNU Chng 2.
5
2.1 Cc kiu d liu c bn
char k t hoc s nguyn 8 bitshort s nguyn 16 bit
long s nguyn 32 bit
int s nguyn di bng 1 word (16 bithoc 32 bit)
float s chm ng 4 byte
double s chm ng 8 byte
long double s chm ng 10 byte
bool gi tr Boolean, true hoc false
wchar_t k t 2 byte, lu bng ch ci quc t
8/8/2019 Chapter02 Data Types Control Structures
6/76
2004 Trn Minh Chu. FOTECH. VNU Chng 2.
6
2.2 Cc php ton c bn
php gn assignation (=)x = 5; //x: lvalue, 5: rvalue
l biu thc c gi tr l gi tr c gn
cc php ton s hc - Arithmetic operators(+, -, *, /, %)
cc php gn kp - Compound assignationoperators
(+=, -=, *=, /=, %=, >>=,
8/8/2019 Chapter02 Data Types Control Structures
7/76
2004 Trn Minh Chu. FOTECH. VNU Chng 2.
7
2.2 Cc php ton c bn
cc php quan h - relational operators( ==, !=, >, =,
8/8/2019 Chapter02 Data Types Control Structures
8/76
2004 Trn Minh Chu. FOTECH. VNU Chng 2.
8
2.2 Cc php gn tt
Cc biu thc gn tt - Assignment expressionabbreviations Php gn cng
c = c + 3; vit tt thnh c += 3;
Cc lnh c dngvariable = variableoperatorexpression;c th c vit li thnh
variableoperator= expression;
Cc php gn khcd -= 4 (d = d - 4)e *= 5 (e = e * 5)
f/= 3 (f = f/ 3)
g %= 9 (g = g % 9)
8/8/2019 Chapter02 Data Types Control Structures
9/76
2004 Trn Minh Chu. FOTECH. VNU Chng 2.
9
2.2 Cc php tng v gim
Php tng - Increment operator (++) c th c dng thay cho c += 1
Php gim - Decrement operator (--) c th c dng thay cho c -= 1
Tng/gim trc Preincrement/Predecrement ++c hoc --c
Gi tr ca bin b thay i, sau biu thc cha n c tnh gi tr.
Biu thc c gi tr l gi tr ca bin sau khi tng/gim
Tng/gim sau - Postincrement/Predecrement c++ hoc c--
Biu thc cha bin c thc hin, sau bin c thay i.
Biu thc c gi tr l gi tr ca bin trc khi tng/gim
8/8/2019 Chapter02 Data Types Control Structures
10/76
2004 Trn Minh Chu. FOTECH. VNU Chng 2.
10
2.2 Cc php tng v gim
V d: nu c = 5 cout
8/8/2019 Chapter02 Data Types Control Structures
11/76
2004 Trn Minh Chu.FOTECH. VNU.
11
fig02_14.cpp
(1 of2)
1 // Fig. 2.14: fig02_14.cpp
2 // Preincrementing andpostincrementing.
3 #include
4
5 using std::cout;
6 using std::endl;7
8 //functionmainbeginsprogramexecution
9 int main()
10 {
11 int c; //declare variable
12
13 //demonstratepostincrement14 c = 5; //assign 5 toc
15 cout
8/8/2019 Chapter02 Data Types Control Structures
12/76
2004 Trn Minh Chu. FOTECH. VNU Chng 2.
12
2.3 Cc php ton logic
c dng lm iu kin trong cc vng lp vlnh if
&& (logical AND) true nu c hai iu kin l true
if ( gender == 1 &&age>= 65 )
++seniorFemales;
|| (logical OR) true nu t nht mt trong hai iu kin l true
if ( semesterAverage>= 90 ||finalExam>= 90 )cout
8/8/2019 Chapter02 Data Types Control Structures
13/76
2004 Trn Minh Chu. FOTECH. VNU Chng 2.
13
2.3 Cc php ton logic
! (logical NOT, ph nh logic logical negation) tr v gi tr true khi iu kin l false, v ngc li
if ( !( grade == sentinelValue ) )cout
8/8/2019 Chapter02 Data Types Control Structures
14/76
2004 Trn Minh Chu. FOTECH. VNU Chng 2.
14
Nhm ln giaphp so snh bng (==) v php gn (=)
Li thng gp Thng khng to li c php (syntax error)
Cc kha cnh ca vn biu thc c gi tr c th c dng lm iu kin
bng khng = false, khc khng = true
Cc lnh gn cng to gi tr (gi tr c gn)
8/8/2019 Chapter02 Data Types Control Structures
15/76
2004 Trn Minh Chu. FOTECH. VNU Chng 2.
15
Nhm ln giaphp so snh bng (==) v php gn (=)
V dif ( 4 == payCode )
cout
8/8/2019 Chapter02 Data Types Control Structures
16/76
2004 Trn Minh Chu. FOTECH. VNU Chng 2.
16
Nhm ln giaphp so snh bng (==) v php gn (=)
Lvalue l biu thc c th xut hin ti v tri ca php gn
xc nh mt vng nh c th c gn tr (i.e, cc bin) x = 4;
Rvalue ch xut hin bn phi php gn
hng, cc gi tr (literal) khng th vit 4 = x;
Lvalue c th c dng nh cc rvalue, nhngchiu ngc li l khng th
8/8/2019 Chapter02 Data Types Control Structures
17/76
2004 Trn Minh Chu. FOTECH. VNU Chng 2.
17
Vit chng trnh
Trc khi vit chng trnh Hiu k bi ton
Lp k hoch gii quyt bi ton
Trong khi vit chng trnh Bit li gii c sn cho cc bi ton con S dng cc nguyn l lp trnh tt
8/8/2019 Chapter02 Data Types Control Structures
18/76
2004 Trn Minh Chu. FOTECH. VNU Chng 2.
18
Thut ton - Algorithm
Cc bi ton tin hc c gii bng cch thc hin mt chui hnh ng theo
mt th t c th
Thut ton: mt quy trnh quyt nh
Cc hnh ng cn thc hin Th t thc hin
V d: cch nu mt mn n
iu khin ca chng trnh Program Control Ch ra th t thc hin cc lnh
8/8/2019 Chapter02 Data Types Control Structures
19/76
2004 Trn Minh Chu. FOTECH. VNU Chng 2.
19
M gi - Pseudocode
M gi: ngn ng khng chnh thc c dng m t thut ton tng t vi ngn ng hng ngy
Khng chy c trn my tnh dng m t chng trnh trc khi vit chng trnh
d chuyn thnh chng trnh C++
ch gm cc lnh chy khng cn khai bo bin
V d:tm s nh hn trong hai s
1. nhp 2 s x,y
2. nu x>y th in y ra mn hnh
3. nu khng, in x ra mn hnh
8/8/2019 Chapter02 Data Types Control Structures
20/76
2004 Trn Minh Chu. FOTECH. VNU Chng 2.
20
Cc cu trc iu khin - Control StructuresKhi nim
Thc thi tun t - Sequential execution Cc lnh c thc hin theo th t tun t
Chuyn iu khin - Transfer of control Lnh tip theo c thc thi khng phi lnh tip theo trong
chui lnh.
3 cu trc iu khin Cu trc tun t - Sequence structure
theo mc nh, chng trnh chy tun t tng lnh
Cc cu trc chn la - Selection structures if, if/else, switch
Cc cu trc lp - Repetition structures while, do/while, for
8/8/2019 Chapter02 Data Types Control Structures
21/76
2004 Trn Minh Chu. FOTECH. VNU Chng 2.
21
Cc cu trc iu khin
Cc t kha ca C++ Khng th dng lm tn bin hoc tn hm
C++ Keywords
Keywords common to theC andC++ programminglanguages
auto break case char const
continue default do double else
enum extern float for goto
if int long register return
short signed sizeof static struct
switch typedef union unsigned void
volatile while
C++ only keywordsasm bool catch class const_cast
delete dynamic_cast explicit false friend
inline mutable namespacenew operator
private protected public reinterpret_cast
static_cast template this throw true
try typeid typename using virtual
wchar_t
8/8/2019 Chapter02 Data Types Control Structures
22/76
2004 Trn Minh Chu. FOTECH. VNU Chng 2.
22
Cc cu trc iu khin
S khi - Flowchart
m t thut ton bng hnh v gm cc k hiu c bit c ni bng cc mi tn(flowlines)
Hnh ch nht (k hiu hnh ng) kiu hnh ng bt k
k hiu oval
Bt u hoc kt thc mt chng trnh,hoc mt on m (hnh trn)
Cc cu trc iu khin c ng 1 u vo, 1 u ra Kt ni u ra ca mt cu trc iu khin vi u vo ca
cu trc tip theo xp chng cc cu trc iu khin
true
false
grade >= 60 print Passed
8/8/2019 Chapter02 Data Types Control Structures
23/76
2004 Trn Minh Chu. FOTECH. VNU Chng 2.
23
Cu trc la chn if
Cu trc la chn - Selection structure chn gia cc tuyn hnh ng khc nhau
v d bng m gi:Ifstudents grade is greaterthan orequal to 60
Print Passed Nu iu kin tha mn (c gi tr true)
lnh Print c thc hin, chng trnh chy tip lnh tip theo
Nu iu kin khng tha mn (c gi tr false)
lnh Print b b qua, chng trnh chy tip
Cch vit tht u dng lm chng trnh d c hn C++ b qua cc k t trng (tab, space, etc.)
8/8/2019 Chapter02 Data Types Control Structures
24/76
2004 Trn Minh Chu. FOTECH. VNU Chng 2.
24
Cu trc la chn if
Dch sang C++Ifstudents grade is greaterthan orequal to 60
Print Passed
if ( grade>= 60 )
cout = 60 print Passed
Mt biu thc bt k uc th c s dng lmiu kin cho la chn.
bng 0- false
khc 0- true
V d:
3 - 4 c gi tr true
8/8/2019 Chapter02 Data Types Control Structures
25/76
2004 Trn Minh Chu. FOTECH. VNU Chng 2.
25
Cu trc chn la if/else
if Thc hin hnh ng nu iu kin tha mn
if/else
thc hin nhng hnh ng khc nhau ty theo iu kin ctha mn hay khng
m giifstudents grade is greaterthan orequal to 60
print Passed
else
print Failed
m C++if ( grade>= 60 )
cout
8/8/2019 Chapter02 Data Types Control Structures
26/76
2004 Trn Minh Chu. FOTECH. VNU Chng 2.
26
Cu trc chn la if/else
php ton iu kin 3 ngi (?:) ba tham s (iu kin, gi tr nu true, gi tr nu false)
m c th c vit:cout = 60 ? Passed : Failed );
truefalse
print Failed print Passed
grade >= 60
Condition Value if true Value if false
8/8/2019 Chapter02 Data Types Control Structures
27/76
2004 Trn Minh Chu. FOTECH. VNU Chng 2.
27
Cu trc chn la if/else
Cc cu trc if/else lng nhau lnh ny nm trong lnh kia, kim tra nhiu trng hp
Mt khi iu kin tha mn, cc lnh khc b b quaifstudents grade is greaterthan orequal to 90
Print A
elseifstudents grade is greaterthan orequal to 80Print B
elseifstudents grade is greaterthan orequal to 70Print C
elseifstudents grade is greaterthan orequal to 60Print D
else
Print F
8/8/2019 Chapter02 Data Types Control Structures
28/76
2004 Trn Minh Chu. FOTECH. VNU Chng 2.
28
Cu trc chn la if/else
V dif ( grade>= 90 ) // 90 andabove
cout = 80 ) // 80-89
cout = 70 ) // 70-79
cout = 60 ) //60-69
cout
8/8/2019 Chapter02 Data Types Control Structures
29/76
2004 Trn Minh Chu. FOTECH. VNU Chng 2.
29
Cu trc chn la if/else
lnh phc compound statement tp lnh bn trong mt cp ngoc
if ( grade>= 60 )cout
8/8/2019 Chapter02 Data Types Control Structures
30/76
2004 Trn Minh Chu. FOTECH. VNU Chng 2.
30
Cu trc lp while
Cu trc lp - Repetition structure hnh ng c lp i lp li trong khi mt iu kin no
cn c tha mn
m giT
rong khi vn cn tn hng trongdanhsch i ch ca tiMua mt hng tip theo v gch tn n ra khi danhsch
vngwhile lp i lp li cho n khi iu kin khng thamn
8/8/2019 Chapter02 Data Types Control Structures
31/76
2004 Trn Minh Chu. FOTECH. VNU Chng 2.
31
Cu trc lp while
V dintproduct = 2;
while ( product
8/8/2019 Chapter02 Data Types Control Structures
32/76
2004 Trn Minh Chu. FOTECH. VNU Chng 2.
32
Thit lp thut ton(iu khin lp bng con m)
Vng lp c iu khin bng con m (counter) Lp n khi con m t n gi tr no
Lp hu hn - Definite repetition s ln lp bit trc
V dMt lp gm 10sinh vin lmmt bi thi. Cho bit cc imthi (snguyn trong khong t 0 n 100). Tnh trung bnhim thi ca lp.
8/8/2019 Chapter02 Data Types Control Structures
33/76
2004 Trn Minh Chu. FOTECH. VNU Chng 2.
33
Thit lp thut ton(iu khin lp bng con m)
M gi cho v d:t tng bng 0
t con m bng 1
Trong khi con m nh hn hoc bng 10Nhp im tip theoCng im vo tngThm 1 vo con n
t trung bnh lp bng tng chia cho 10
In trung bnh lp
Tip theo: M C++ cho v d trn
8/8/2019 Chapter02 Data Types Control Structures
34/76
2004 Trn Minh Chu.FOTECH. VNU.
34
fig02_07.cpp
(1 of2)
1 // Fig. 2.7: fig02_07.cpp
2 //Classaverageprogramwithcounter-controlledrepetition.
3 #include
4
5 using std::cout;
6 using std::cin;
7 using std::endl;
8
9 //functionmainbeginsprogramexecution
10 int main()
11 {
12 int total; //sumof gradesinputbyuser13 int gradeCounter; //numberof gradetobeenterednext
14 int grade; // grade value
15 int average; //averageof grades
16
17 //initializationphase
18 total = 0; //initializetotal
19 gradeCounter = 1; //initializeloopcounter20
8/8/2019 Chapter02 Data Types Control Structures
35/76
2004 Trn Minh Chu.FOTECH. VNU.
35
fig02_07.cpp
(2 of2)
fig02_07.cpp
output (1 of1)
21 //processing phase
22 while ( gradeCounter grade; //read gradefromuser
25 total = total + grade; //add gradetototal
26 gradeCounter = gradeCounter + 1; //incrementcounter
27 }
28
29 //terminationphase
30 average = total/10; //integerdivision
31
32 //displayresult33 cout
8/8/2019 Chapter02 Data Types Control Structures
36/76
2004 Trn Minh Chu. FOTECH. VNU Chng 2.
36
Thit lp thut ton(iu khin lp bng lnh canh)
Gi s bi ton tr thnh:Vitmt chng trnh tnh im trung bnh ca lp, chngtrnhsx l mtslng im ty mi khi chy chngtrnh.
S sinh vin cha bit Chng trnh s lm th no bit khi no th kt thc?
Gi tr canh K hiu Kt thc ca d liu vo
Vng lp kt thc khi nhp canh Canh c chn khng b ln vi d liu vo thngthng
trong trng hp ny l -1
8/8/2019 Chapter02 Data Types Control Structures
37/76
2004 Trn Minh Chu. FOTECH. VNU Chng 2.
37
Thit lp thut ton(iu khin lp bng lnh canh)
Thit k t trn xung, lm mn tng bc Bt u bng m gi cho mc cao nht
Tnh trung bnh im thi ca lp
Chia thnh cc nhim v nh hn, lit k theo th t
Khi to cc binNhp, tnh tng, v m cc im thi
Tnh v in trung bnh im thi
8/8/2019 Chapter02 Data Types Control Structures
38/76
2004 Trn Minh Chu. FOTECH. VNU Chng 2.
38
Thit lp thut ton(iu khin lp bng lnh canh)
Nhiu chng trnh c 3 pha Khi to - Initialization
Khi to cc bin chng trnh
X l - Processing
Nhp d liu, iu chnh cc bin trong chng trnh Kt thc - Termination
Tnh v in kt qu cui cng
Gip vic chia nh chng trnh lm mn t trn xung
8/8/2019 Chapter02 Data Types Control Structures
39/76
2004 Trn Minh Chu. FOTECH. VNU Chng 2.
39
Thit lp thut ton(iu khin lp bng lnh canh)
Lm mn pha khi toKhi to cc bin
thnh
Khi to tng bng 0
Khi to bin m bng 0
X lNhp, tnh tng, v m cc im thi
thnh
Nhp im u tin (c th l canh)
Trong khi ngi dng cn cha nhp canh
Cng im va nhp vo tng
Cng thm 1 vo bin m im
Nhp im tip theo (c th l canh)
8/8/2019 Chapter02 Data Types Control Structures
40/76
2004 Trn Minh Chu. FOTECH. VNU Chng 2.
40
Thit lp thut ton(iu khin lp bng lnh canh)
Kt thcTnh v in trung bnh im thi
thnh
Nu con m khc 0
t trung bnh bng tng chia cho con m
In gi tr trung bnh
Nu khng
In Khng nhp im no
Tip theo: chng trnh C++
8/8/2019 Chapter02 Data Types Control Structures
41/76
2004 Trn Minh Chu.FOTECH. VNU.
41
fig02_09.cpp
(1 of3)
1 // Fig. 2.9: fig02_09.cpp
2 //Classaverageprogramwithsentinel-controlledrepetition.
3 #include
4
5 using std::cout;
6 using std::cin;
7 using std::endl;
8 using std::fixed;
9
10 #include //parameterizedstreammanipulators
11
12 using std::setprecision; //setsnumericoutputprecision13
14 //functionmainbeginsprogramexecution
15 int main()
16 {
17 int total; //sumof grades
18 int gradeCounter; //numberof gradesentered
19 int grade; // grade value20
21 double average; //numberwithdecimalpointforaverage
22
23 //initializationphase
24 total = 0; //initializetotal
25gradeCounter
= 0;//
initialize
loop
counter
D liu kiu double dng biu din s thp phn.
8/8/2019 Chapter02 Data Types Control Structures
42/76
2004 Trn Minh Chu.FOTECH. VNU.
42
fig02_09.cpp
(2 of3)
26
27 //processing phase
28 // getfirst gradefromuser
29 cout > grade; //read gradefromuser
3132 //loopuntilsentinel valuereadfromuser
33 while ( grade!= -1 ) {
34 total = total + grade; //add gradetototal
35 gradeCounter = gradeCounter + 1; //incrementcounter
36
37 cout > grade; //readnext grade
39
40 }//endwhile
41
42 //terminationphase
43 //ifuserenteredatleastone grade ...
44 if ( gradeCounter!= 0 ) {45
46 //calculateaverageofall gradesentered
47 average = static_cast< double >( total ) / gradeCounter;
48
static_cast() coi total nh mt double tm thi (casting).
Cn thit v php chia s nguyn b qua phn d.gradeCounter l mt bin int, nhng n c nng ln kiu double.
43
8/8/2019 Chapter02 Data Types Control Structures
43/76
2004 Trn Minh Chu.FOTECH. VNU.
43
fig02_09.cpp
(3 of3)
fig02_09.cpp
output (1 of1)
49 //displayaveragewithtwodigitsofprecision
50 cout
8/8/2019 Chapter02 Data Types Control Structures
44/76
2004 Trn Minh Chu. FOTECH. VNU Chng 2.
44
Cc cu trc iu khin lng nhau
Pht biu bi tonMt trng c danhsch ktqu thi (1 = , 2 = trt) ca10sinh vin. Vitmt chng trnh phn tch ktqu thi.
Nu c nhiu hn 8sinh vin th in ra mn hnh dngch Tng tin hc ph".
Lu Chng trnh x l 10 kt qu thi
s ln lp c nh, s dng vng lp iu khin bng bin m
C th s dng hai con m Mt con m m s lng
Mt con m khc m s lng trt
Mi kt qu thi ch l 1 hoc 2 Nu khng phi 1 th coi l 2
45
8/8/2019 Chapter02 Data Types Control Structures
45/76
2004 Trn Minh Chu. FOTECH. VNU Chng 2.
45
Cc cu trc iu khin lng nhau
Phc tho mc cao nht - Top level outlineAnalyzeexamresults anddecide iftuitionshouldberaised
Lm mn ln mt - First refinementInitialize variables
Input the ten quiz grades andcount passes andfailuresPrint asummaryoftheexamresults anddecide iftuitionshouldberaised
Lm mn - RefineInitialize variables
to
Initialize passes tozero
Initializefailures tozero
Initializestudent countertoone
46
8/8/2019 Chapter02 Data Types Control Structures
46/76
2004 Trn Minh Chu. FOTECH. VNU Chng 2.
46
Cc cu trc iu khin lng nhau
RefineInput the ten quiz grades andcount passes andfailures
to
Whilestudent counteris less than orequal to tenInput the nextexamresult
Ifthestudent passed
Addone to passesElse
Addone tofailures
Addone tostudent counter
47
8/8/2019 Chapter02 Data Types Control Structures
47/76
2004 Trn Minh Chu. FOTECH. VNU Chng 2.
47
Cc cu trc iu khin lng nhau
tip tc lm mnPrint asummaryoftheexamresults anddecide iftuitionshould
beraised
to
Print the numberofpasses
Print the numberoffailuresIfmore than eightstudents passed
Print Raise tuition
Program next
48
8/8/2019 Chapter02 Data Types Control Structures
48/76
2004 Trn Minh Chu.FOTECH. VNU.
48
fig02_11.cpp
(1 of2)
1 // Fig. 2.11: fig02_11.cpp
2 //Analysisofexaminationresults.
3 #include
4
5 using std::cout;
6 using std::cin;
7 using std::endl;
8
9 //functionmainbeginsprogramexecution
10 int main()
11 {
12 //initialize variablesindeclarations13 int passes = 0; //numberofpasses
14 int failures = 0; //numberoffailures
15 int studentCounter = 1; //studentcounter
16 int result; //oneexamresult
17
18 //process 10 studentsusing counter-controlledloop
19 while ( studentCounter result;
24
49
8/8/2019 Chapter02 Data Types Control Structures
49/76
2004 Trn Minh Chu.FOTECH. VNU.
49
fig02_11.cpp
(2 of2)
25 //ifresult 1,incrementpasses; if/elsenestedinwhile
26 if ( result == 1 ) //if/elsenestedinwhile
27 passes = passes + 1;
28
29 else //ifresultnot 1,incrementfailures
30 failures = failures + 1;31
32 //incrementstudentCountersoloopeventuallyterminates
33 studentCounter = studentCounter + 1;
34
35 }//endwhile
3637 //terminationphase; displaynumberofpassesandfailures
38 cout
8/8/2019 Chapter02 Data Types Control Structures
50/76
2004 Trn Minh Chu.FOTECH. VNU.
50
fig02_11.cpp
output (1 of1)
Enterresult (1 = pass, 2 = fail): 1
Enterresult (1 = pass, 2 = fail): 2
Enterresult (1 = pass, 2 = fail): 2
Enterresult (1 = pass, 2 = fail): 1
Enterresult (1 = pass, 2 = fail): 1
Enterresult (1 = pass, 2 = fail): 1
Enterresult (1 = pass, 2 = fail): 2
Enterresult (1 = pass, 2 = fail): 1
Enterresult (1 = pass, 2 = fail): 1
Enterresult (1 = pass, 2 = fail): 2
Passed6
Failed
4
Enterresult (1 = pass, 2 = fail): 1
Enterresult (1 = pass, 2 = fail): 1
Enterresult (1 = pass, 2 = fail): 1
Enterresult (1 = pass, 2 = fail): 1
Enterresult (1 = pass, 2 = fail): 2
Enterresult (1 = pass, 2 = fail): 1Enterresult (1 = pass, 2 = fail): 1
Enterresult (1 = pass, 2 = fail): 1
Enterresult (1 = pass, 2 = fail): 1
Enterresult (1 = pass, 2 = fail): 1
Passed 9
Failed 1
Raisetuition
51
8/8/2019 Chapter02 Data Types Control Structures
51/76
2004 Trn Minh Chu. FOTECH. VNU Chng 2.
51
Nhng im quan trng vvng lp iu khin bng con m
vng lp iu khin bng con m i hi Tn ca bin iu khin(control variable) hay bin m
(loop counter)
Gi tr khi to ca bin iu khin
iu kin kim tra gi tr cui cng Tng/gim bin m khi thc hin vng lp
int counter = 1; // initialization
while ( counter
8/8/2019 Chapter02 Data Types Control Structures
52/76
2004 Trn Minh Chu.FOTECH. VNU.
52
fig02_16.cpp
(1 of1)
1 // Fig. 2.16: fig02_16.cpp
2 //Counter-controlledrepetition.
3 #include
4
5 using std::cout;
6 using std::endl;7
8 //functionmainbeginsprogramexecution
9 int main()
10 {
11 int counter = 1; //initialization
1213 while ( counter
8/8/2019 Chapter02 Data Types Control Structures
53/76
2004 Trn Minh Chu. FOTECH. VNU Chng 2.
53
Cu trc vng lp for
Dng tng qut ca vng for
for ( khi_to; iu_kin_lp; tng/gim )
lnh
V dfor( intcounter = 1; counter
8/8/2019 Chapter02 Data Types Control Structures
54/76
2004 Trn Minh Chu.FOTECH. VNU.
54
fig02_17.cpp
(1 of1)
1 // Fig. 2.17: fig02_17.cpp
2 //Counter-controlledrepetitionwiththeforstructure.
3 #include
4
5 using std::cout;
6 using std::endl;7
8 //functionmainbeginsprogramexecution
9 int main()
10 {
11 // Initialization,repetitionconditionandincrementing
12 //are
all
included
in
the
for
structure
header
.13
14 for ( int counter = 1; counter
8/8/2019 Chapter02 Data Types Control Structures
55/76
2004 Trn Minh Chu. FOTECH. VNU Chng 2.
55
Cu trc vng lp for
vng for thng c th vit c thnh vngwhile tng ng
khi_to;
while ( iu_kin_lp){
lnh
tng/gimbin m;}
Khi to v tng bin m
nu s dng nhiu bin m, s dng du phy tchfor (inti = 0, j = 0; j + i
8/8/2019 Chapter02 Data Types Control Structures
56/76
2004 Trn Minh Chu.FOTECH. VNU.
fig02_20.cpp
(1 of1)
fig02_20.cpp
output (1 of1)
1 // Fig. 2.20: fig02_20.cpp
2 // Summationwithfor.
3 #include
4
5 using std::cout;
6 using std::endl;7
8 //functionmainbeginsprogramexecution
9 int main()
10 {
11 int sum = 0; //initializesum
12
13 //sumevenintegersfrom 2 through 100
14 for ( int number = 2; number
8/8/2019 Chapter02 Data Types Control Structures
57/76
2004 Trn Minh Chu. FOTECH. VNU Chng 2.
V d s dng vng for
Chng trnh tnh li kp (compound interest) Mt ngi u t $1000.00 vo mt ti khon tit kim vi li sut
5%. Gi s tin li c gp vi vn trong ti khong, tnh v in ra stin t rong ti khon vo cui mi nm trong vng 10 nm. Sdngcng thc sau t nh cc khon tin :
a = p(1+r)
p : khon u t ban u (i.e., the principal),r: li sut hng nm, (interest rate)
n : s nm, va : lng tin c trong ti khon (amount on deposit)vo cui nm th n
n
581 // Fi 2 21 fi 02 21
8/8/2019 Chapter02 Data Types Control Structures
58/76
2004 Trn Minh Chu.FOTECH. VNU.
fig02_21.cpp
(1 of2)
1 // Fig. 2.21: fig02_21.cpp
2 //Calculating compoundinterest.
3 #include
4
5 using std::cout;
6 using std::endl;7 using std::ios;
8 using std::fixed;
9
10 #include
11
12 usingstd
::setw
;13 using std::setprecision;
14
15 #include //enablesprogramtousefunctionpow
16
17 //functionmainbeginsprogramexecution
18 int main()
19 {20 double amount; //amountondeposit
21 double principal = 1000.0; //starting principal
22 double rate = .05; //interestrate
23
header cn chohmpow (chng trnh skhng dch nu khng c khai
bo ny).
8/8/2019 Chapter02 Data Types Control Structures
59/76
60Year Amount on deposit
8/8/2019 Chapter02 Data Types Control Structures
60/76
2004 Trn Minh Chu.FOTECH. VNU.
fig02_21.cpp
output (1 of1)
Year Amountondeposit
1 1050.00
2 1102.50
3 1157.63
4 1215.51
5 1276.28
6 1340.10
7 1407.10
8 1477.46
9 1551.33
10 1628.89
Cc s c cn phi do cc lnh
setw (vi tham s c gi tr 4 v 21).
61
8/8/2019 Chapter02 Data Types Control Structures
61/76
2004 Trn Minh Chu. FOTECH. VNU Chng 2.
Cu trc a la chn switch
switch
Test bin vi nhiu gi tr chui cc nhn case trng hp default khng bt buc
switch ( variable ) {
case value1: //takenif variable == value1statements
break; //necessarytoexitswitch
case value2:
case value3: //takenif variable == value2 or == value3
statementsbreak;
default: //takenif variablematchesnoothercases
statementsbreak;
}
62
8/8/2019 Chapter02 Data Types Control Structures
62/76
2004 Trn Minh Chu. FOTECH. VNU Chng 2.
Cu trc a la chn switch
true
false
.
.
.
case a case a action(s) break
case b case b action(s) break
false
falsecase z
case z action(s) break
true
true
default action(s)
63
8/8/2019 Chapter02 Data Types Control Structures
63/76
2004 Trn Minh Chu. FOTECH. VNU Chng 2.
Cu trc a la chn switch
V d sp ti Chng trnh c xp loi im (A-F) Hin s lng mi xp loi c nhp
Chi tit v cc k t Cc k t n thng c lu bng kiu d liu char
char: s nguyn 1-byte, c th c lu di dng cc gi tr int C th coi k t l int hoc char
97 l biu din dng s ca ch a thng (ASCII) dng cp nhy n ly biu din ch ca k t
cout
8/8/2019 Chapter02 Data Types Control Structures
64/76
2004 Trn Minh Chu.FOTECH. VNU.
fig02_22.cpp
(1 of4)
1 // Fig. 2.22: fig02_22.cpp
2 //Counting letter grades.
3 #include
4
5 using std::cout;
6 using std::cin;7 using std::endl;
8
9 //functionmainbeginsprogramexecution
10 int main()
11 {
12 int grade; //one grade
13 int aCount = 0; //numberofAs
14 int bCount = 0; //numberof Bs
15 int cCount = 0; //numberofCs
16 int dCount = 0; //numberofDs
17 int fCount = 0; //numberof Fs
18
19 cout
8/8/2019 Chapter02 Data Types Control Structures
65/76
66
43 case 'D': // grade was uppercase D
8/8/2019 Chapter02 Data Types Control Structures
66/76
2004 Trn Minh Chu.FOTECH. VNU.
fig02_22.cpp
(3 of4)
43 case D : // gradewasuppercaseD
44 case 'd': //orlowercased
45 ++dCount; //incrementdCount
46 break; //exitswitch
47
48 case 'F': // gradewasuppercase F49 case 'f': //orlowercasef
50 ++fCount; //incrementfCount
51 break; //exitswitch
52
53 case '\n': //ignorenewlines,
54 case '\t': //tabs,
55 case ' ': //andspacesininput
56 break; //exitswitch
57
58 default: //catchallothercharacters
59 cout
8/8/2019 Chapter02 Data Types Control Structures
67/76
2004 Trn Minh Chu.FOTECH. VNU.
fig02_22.cpp
(4 of4)
67 //outputsummaryofresults
68 cout
8/8/2019 Chapter02 Data Types Control Structures
68/76
2004 Trn Minh Chu.FOTECH. VNU.
fig02_22.cpp
output (1 of1)
Entertheletter grades.
EntertheEOF charactertoendinput.
a
B
c
CA
d
f
C
E
Incorrectletter gradeentered. Enteranew grade.
D
A
b
^Z
Totalsforeachletter gradeare:A: 3
B: 2
C: 3
D: 2
F: 1
69
8/8/2019 Chapter02 Data Types Control Structures
69/76
2004 Trn Minh Chu. FOTECH. VNU Chng 2.
Cu trc lp do/while
Tng t cu trcwhile Kim tra iu kin tip tc lp
cui, khng kim tra u
Thn vng lp chy t nht mtln
Cng thcdo {
statements
}while ( condition );
true
false
action(s)
condition
8/8/2019 Chapter02 Data Types Control Structures
70/76
71
8/8/2019 Chapter02 Data Types Control Structures
71/76
2004 Trn Minh Chu. FOTECH. VNU Chng 2.
Cc lnh break v continue
break Thot ngay ra khi cc cu trc while, for, do/while,
switch
Chng trnh tip tc chy ti lnh u tin ngay sau cutrc
thng c s dng Thot khi vng lp sm hn bnh thng b qua phn cn li ca switch
721 // Fig. 2.26: fig02_26.cpp
8/8/2019 Chapter02 Data Types Control Structures
72/76
2004 Trn Minh Chu.
FOTECH. VNU.
fig02_26.cpp
(1 of2)
2 // Using thebreakstatementinaforstructure.
3 #include
4
5 using std::cout;
6 using std::endl;
78 //functionmainbeginsprogramexecution
9 int main()
10 {
11
12 int x; //xdeclaredheresoitcanbeusedaftertheloop
13
14 //loop 10 times
15 for ( x = 1; x
8/8/2019 Chapter02 Data Types Control Structures
73/76
2004 Trn Minh Chu. FOTECH. VNU Chng 2.
Cc lnh break v continue
continue c dng trong while, for, do/while
b qua phn cn li ca thn vng lp
chy tip ln lp tip theo
vi cc vngwhile v do/while thc hin kim tra iu kin lp ngay sau lnh continue
vi vng for biu thc tng/gim bin m c thc hin
sau , iu kin lp c kim tra
74
1 // Fig. 2.27: fig02_27.cpp
8/8/2019 Chapter02 Data Types Control Structures
74/76
2004 Trn Minh Chu.
FOTECH. VNU.
fig02_27.cpp
(1 of2)
2 // Using thecontinuestatementinaforstructure.
3 #include
4
5 using std::cout;
6 usingstd
::endl
;7
8 //functionmainbeginsprogramexecution
9 int main()
10 {
11 //loop 10 times
12 for ( int x = 1; x
8/8/2019 Chapter02 Data Types Control Structures
75/76
2004 Trn Minh Chu. FOTECH. VNU Chng 2.
Lp trnh cu trcStructured-Programming
Lp trnh cu trc Structured programming Chng trnh d hiu, test, tm li (debug) v d sa i hn Cc quy tc lp trnh cu trc
Ch s dng cc cu trc iu khin mt u vo mt u ra
Quy tc1) Bt u bng mt s khi n gin nht
2) Mi hnh ch nht (hnh ng) c th c thay bng mtchui gm 2 hnh ch nht khc
3) Mi hnh ch nht (hnh ng) c th c thay bng mt cu
trc iu khin ty (tun t, if, if/else, switch, while,do/while hoc for)
4) Cc quy tc 2 v 3 c th c p dng nhiu ln v theo tht ty
76
Lp trnh cu trc
8/8/2019 Chapter02 Data Types Control Structures
76/76
Lp trnh cu trcStructured-Programming
Qui tc 3
Qui tc 3Qui tc 3
M t quy tc 3 (thay mt hnh ch nht ty bng mt cu trc iu khin)