ThS.

TItU KIM CUONG

,I' ,

GIAOTRINH

rtGOrt rtGU L8P TRirtH C

(Sacli dung cho cac truang ddo tao hf Trung h9C chuyen nghiep)

NHA XUAT BAN GIAO DlJC

617

GD _ 04 65 !lIS - 04

Mil so: 6H159M4

lm~m~~u---------------------

Niim 2002, V(I Guio due Chuyen nghi~p - Bij Gicio due va Dao t{W da. phOi h(jp vm Nha xufit bdn Giao due xufit bdn 21 gjcio trinh phuc V(l cho dao t~o h~ THCN. Cae guio trinh tren dii dll,!c nhiiu truimg sit dung va hoan nghenh: De' tilp t(lC bO'sung ngu6n gicio trinh dang con thieu, V(l Giao due Chuyen nghi~p phDi hop cimg Nha xufit ban Gitio due tilp tlfc bien so~n mijt stl gicio trinh, sdch: tham kiuio phuc V(l cho dao tao if ccic nganh : Di~n -Di~n tit, Tin hoc, Khai thcic ca khi. Nhitng gicio trinh nay truoc khi bien soan, V¥ Giao due Chuyen ngh~p aa. gin d~ cuong v~ tren 20 trtdmg va to' ciuic hiji thsio, Ifiy y kiln dong gop vi n(ji dung d~ cuang cdc giao trinh noi tren. Tren co sif nghitm. cUu y kiln dong gop cua cac truang, nhom. tcic gia da. dillu chlnh. ni)i dung cac gitio trinh cho phil hrJp vdi yeu cdu thljc tiin han.

Vdi kinh nghi~m giang d~y, kien thuc ticli Iuy qua nhie'u nom, cac tdc gia dii co' gang dl nhitng n(ji dung dlif/C trinh My la nhitng kien thtic ca ban nhfit nhung vdn c~p nh~t dlif/c vdi nhfing tien b(j cua khaa h9C ky thu~t, udi thuc tt san xufit. Niji dung cUa giao trinli cOn tao Slj lien thong til DfJY nghi len THCN.

Ikic giao trinh dl1f/C bien sopn thea hltfJng md, kien thuc rijng ua c(/ g&ng chi ra tinh. ang d(lng cria niji dung dltf!C trinh My. Tren. co Sd d6 tao dillu ki~n dl cdc trltClng sa dlfng mgt cach phil h(jp vm dillu ki~n co Sd vt,it coot phuc v¥ thuc hanh, thuc tt,ip va diJ,c diem cua cdc nganh, chuyen nganh dao tao.

De'vi¢c a6i mdi phl1dng phap Jpy va hoc thea chi dao cua B9 Gicio due va Dao tao nhdm ndng cao cMit Iltf"/ng d9-y va hQC, cac truang can trang bi du stich. cho thlt vi~n va tao dMu ki~n ae' gicio vien va hoc sinh co au sach thea nganh dao tao. Nhitng gido trinh nay ciing Ia tai l~u tham khao tot cho h9C sinh dii t6i nghi~p can dao tao lai, nluin. vien ky thu9-t dang true tiip san xufit.

Ctic gicio trinh aa. xudt ban kMng the'tranh khai nhftng sai sot. Rtft mong cdc thriy, co giao, ban. doc gop Y dllan xudt ban sau dltf!C tot han. Mt;Ji gop y sin gm v~ : Cong ty cs phdn scich Dai hoc - Dt;ty nghil25 Han Thuyen - Ha Niji.

vu GIAo Dl)C CHuvtN NGHltp - NXB GIAO Dt)C

3

Mudii'u

Gido due chuyen nghi1p Wl day ngh/Ia mot trong nhiing linl: vlfc cdn dUIJC quan ram hang ddu trong tien trinh phat t,-ien cua mot ddt nuac, M¢t trong nhiing nhan todong vai tro quyet diuh defl chat luang cua dao tao do fa giao trinh dung de' gidng day trong IIlIa truang. Khac vDi giao due dai hoc, gido due chuyen nghiep doi hoi pluii co 51! ket h'1P nhudn nhuyen giila Ii thuyet va thuc hanh. Nhiing kiln thuc li thuyer dd JU?C phdi duac ap dung ngay trong thuc tli'thong qua cdc vi du cu till Tuy nhien, khong vi thema n¢i dung li {huyet bi edt giam di, nguoc lai cdn phdi dao sau, md rong them de'vi¢c ap dung ella nguai hoc khong may 1I1(IC, dap khuon, ma phdi sang tao va chu dong dua tren nhiing hiti'u biet sdu sac cua bdn than, co nhu the' khi tot Ilghi¢p mai dap ung duac nhiing nhu cdu IIgay cang cao ella xil Mi.

Ngon ng£( lap trinh C fa mot trong nhling ngon ngfl kilo su dung, doi hoi nhieu thai gian va cong suc de' e6 the'lam clue n6, bien no thuc su trd thanh mot cong cu dac luc trong cuoc song ngJui nghi¢p cua moi nguoi, Do do, trong khuon kho' 60 tiet, tac gid cd gallg bien SOIJn tren tinh thdn ngan g911, de hie'll va ddy dli dua tren quan diim day hoc tich cue ~ dIJY hoc dinli huang hanl: dong. Cac kiln thuc trong toan b¢ gido trinh co moi lien h¢ chat che, logic. Cdc n¢i dung dua ra duoc minh hoa CI;i the', true quail va duac phdn ticli sdu sac nhdm giup nguoi hoc co 111f/ Itilu ky han cdc tinh huang c6 vall de' va thuang gr)p trong cong viec.

T oan bt} giao trinh bao go'm bay chuang va bon phu luc chua dung tuong do'i ddy du cdc valz de' ca bdn nluit cua ligon IIgi7lqp trinh C, cdc loai vi du va bai tdp chon loc cung mot so' va'l de" lien quan, giup nguoi hoc c6 klui nang sti dung thanh thao ligon IIgil nay troug viec gidi quye: mot so- lap bai loan thong dung trong thuc te~ DJu moi chuang, deu chi ra cdc muc tieu CI.l thi can dat duac clla ell/tang do nham ghip ngui'ri hoc co tlu! dinh huang tot hall trong viec hoc cung nhu giup clio gido vien co thi tham kluio trong qua triuh giang day ella minh.

Gido trinli duac bien SO(J1l clio ddi tuang chinh fa hoc sinh THCN, KI tllUt;it vien tin hoc, tuy nhien no ciing c6 the'lii tai lieu tham khao bi;' ich clio bdc dai hoc va nhiing IIgui'ri quail tam.

Mijc du dd co' gang nhieu trong qua trill" bien soan gido trinh nay, nhung chac chan khong tranh khoi co nhiaig thieu sot. Rat mong nJuj.1I duac y kiln dong gop clla d¢c gid vii cdc dong nghiep de' gitu: trinh ngay cang hoan thien han. MQi y kien dong gop xin gui vii' Nita xudr ball Gido due ~ 81 Trdn Hung Dao, Hii Noi.

TAc GIA

4

Chuang 1

T6NG QUAN VE NGON NGU L~P TRINH C

MVC rttu eVA CHUONG NAy

;.- Bid mot vai 111ft hell .'I'll phat trie'n ciing nhu uifc diem eua ngon ngi"i lap trlnh C dong tillY, hii'll va hilt each sri dung cdc kMi niem co ban trong ngon IIg Ii I dp trinn C.

;.- Bilt each .'I'll dung moi truong ket IU;p ala Turbo C de' viet WJ c!U1Y mot chuang trinh C dan gidn then cdu true chudn.

1.1. qCH sir PHkr TRIEN vA D~C DIEM NG()N NGU L~P TRiNH C

Tien than cua ngon ngCi' lap trinh C lit ngon ngir BCPL (Basic Conbined Programming Language) do Martin Richards nghien cuu, Anh huang cua ngon ngu BCPL len ngon ngu lap trinh C gian tiep thong qua ngon ngu B, do Ken Thompson viet nam 1970 cho he dieu hanh UNIX cha y tren ho rna y tinh PDP-7.

Nhu cau cai tien va phat trien cho UNIX da thiic dAy Dennis Ritchie va Brian Kernighan sang tao ra ngon ngtr l*p trlnh C ngay tai phong thi nghiem BELL (Hoa Kl) vao dau nhimg nam 70 nham rnuc dieh ban dau la phat trien mot ngon ngCi' he th6ng mern deo thay the cho ngon ngtt Assembly v6n nang ne va "cung nhac" voi cac thiet bi phan ctmg.

Ngon ngilI*p trinh C dac biet khac voi ngon ngn BCPL va ngon ngtr B C1 cho: ngon ngir BCPL va ngon ngir B chi eo duy nhat mot ki~u du lieu la tit may, trong khi do ngon ngtt lap trinh C da co cac d6i urong dft lieu co ban nhu ki tu, cac kilu s{/ nguyen va cac kilu sothuc. Dac bier con tro trong ngon ngtr lap trinh C tao ra them duqc r!'lt nhieu tru viet,

Sau khi ra doi, d~c biet thanh cong voi he dieu hanh UNIX, ngon ngtt lap trinh C bat dau diroc pho bien rong rai va ngiroi ta da nhan thay sue manh ella no. C la ngon ngu lap trinh nrrmg d6i van nang, eo muc d(l thich nghi eao, mem deo, Khac voi ngon ngtr Pascal, I;). ngon ngfr lap trinh co cau true rat chat che va tlurong diroc dung M giang day ve lap trinh dac biet trong cac tnrong dai hQC, thi ngon ngil l~p trinh C lai diroc Slr dung rong rai trong cac linh virc chuyen nghiep VI tinh hieu qua va mem den ella no.

Vao nhirng nam 80, do nhu cau [rang viec xir H dii lieu ngay mot cao, cac chirong trinh viet ra ngay mot phirc tap, viec bao duong chuang trinh ngay mot kho

5

khan da: dan den mot phong each lap trinh mei -l~p trinh huang d6i nrong (OOPObject Oriented Programming) xuat hien va ngOn ngir Iap trlnh C bat dau dllQ'e trang bi them kha nang lap trlnh huong d6i nrong, ngon ngtf lap trlnh C" ra dCri tir do va ngay cang chiern uu the.

Hien nay eo rAt nhieu b¢ chuang trlnh bien dich (Compiler) va lien ket (Link) eho ngon ngir lap trinh C cua nhieu hang khac nhau va moi bo chuang trlnh deu eo nhtrng uu, nhuoc diem rieng, Xep 0 vi tri hang dau eo tM k~ den Turbo C cua hang Borland, MS C cua hang Microsoft, ZOKfECH·C cua hang SYSMANTEC. PMn mem Turbo C duoc sir dung kha rong rai VI no cung cap cho ngiroi dung mot thu vien kha day du cac ham vao ra, truy nhap va d6 h0<:L. Tuy nhien kha nang tOi uu mii cua n6 kh6ng bang MS C. Trong giao trlnh nay cluing toi sir dung TurboC do tinh tien lei va pho dung cua no,

J .2. cAe KHAI NI~M co BAN

1.2.1. Tap ki h.r dung trong ngon ngu lap trlnh C

Cilng nhu ngon ngir tu nhien, moi ngon ngtr l~p trlnh deu duoc xay dung ttr mot b6 ki tv nao do goi la bang chir cai cua ngon ngit. Cac ki t1,l" nay ducc ket hop voi nhau thea nhicu each, theo nhieu quy tAc khac nhau tao nen cac til, cac tlr lai duoc lien ket voi nhau theo mot quy tae nao d6 (ph(~ thuoc van cdc ngon ngii khac nhaui d~ t<:LO thanh cac cau lenh, M6i chuang trinh se bao g6m nhieu cau l¢nh diroc dien dat theo logic cua mot thuat toan nao d6 M giai quyet bai roan dang xet, Ngon ngit lap trlnh C duoc xay dung tren b¢ ki nr sau day:

26 crur cal hoa A, S, C, ... Z va 26 crnr cal thuong a, b, c, '" z cua b¢ chir cal tieng Anh.

10 chir s6 0, 1, 2, ... 9

Cac kf hieu toan h9C: + - * I = ( )

Ki tu g~ch n6i ",.' (chu y khac vai ki tu '- ')

Cac kf hi~u di,le biet khac d6 180 cac ki tv : , . ; [ 1 { } ? ! & \ % # $ - > < 1\ " .. , . va I.

Dau each' , (ki tq trong) diroc dung nhu ki t1,I" phan tach gitta cac tit trong chuang trinh va kh6ng c6 y nghia gl trong moi cau lenh, cac til trong ngon ngu l~p trinh C c6 the diroc phan tach boi mot hay nhieu dau each.

Khi viet chuang trinh ta khong duoc phep sir dung bat kl mot ki t1,l" nao khac ngoai cac ki t\f k~ tren.

1.2.2. Tit khoa

Tel khoa la nlurng tir diinh rieng cua ngon ngfr l~p trinh C duoc dinh nghia tnroc voi nhilng y nghia hoan toan xac dinh. Tit khoa thuong duoc dung M khai baa, dinh nghia cac ki~u dir lieu, dinh nghia ra cac toan tir, cac ham va viet cac cau lenh ... Do d6 khi viet chuang trinh ta khong th~ dung tit khoa d~ d~t ten C~10 cac hang, bien, rnang hay ham ...

Chu y Trung ngon"gil If!.p trinh c til' khoa bao gio ciing d~ viet bAng chir tln1bng.

6

Bang 1.1: Cac til khoa thong dung trong ngon ngii lap trlnh C

asm do goto register typedef
break double huge return union
case else if short unsigned
cdecl enum int signed void
char extern interrupt sizeof volatile
canst far long static while
continue float near struct
default for pascal switch M6i til khoa se c6 cu phap Slr dung rieng va trong chuang trinh ta phai tuan thu dung thea en phap d6. Cach sir dung cua cac tir khoa thong dung nhat se diroc Un hrot gioi thieu trong giao trinh.

1.2.3. Cach d~t ten trong ngon ngu l:,ip trmh C

Ten la mot khai niem rat quan trong dung dS XRC dinh cac dai hrong khac nhau trong m6i chuang trinh nhu ten hang, ten bien, ten mang, ten can tnic, ten can tro, ten ~p, ten nhan, ten ham ... M6i ten trong ngon ngu lap trinh C duoc quy uoc la m¢t di'Y cac ki tl! chi bao g6m che cai, chit s6 va dfiu gach n6i. Kf ur dau tien cua ten bit buoc phai la mot chif cai hoac dlfu gach n6i.

Sau ddy Ia m9t so ~i dl:' ~e ten:

6.: KhOng hop l~ vi khong phai chu cai, chtr s6 hoac dau gach n6i. 2_delta: Khong hop l¢ vi bit dAu bAng chu 56.

switch: Khong hop l¢ vltrung vOi til khoa,

Del ta: KhOng bop l¢ vi co khoang each b gitra,

Del -ta: Khong hop l¢ VI sir dung da':u gach ngang '-' .

Del ja: Hqp l¢. . .

_Modul_asm_l : Hop 1¢.

Trunggian L; Hop l~ ...

Khac voi Pascal, ten trong ngOn ngtr l~p trlnh C phan biet gitra chu hoa va chfr thuong, vi du cac ten abc, Abc, ABc, ABC ... 1a hoan toan khac nhau.

M9t s61rmy khi d4t ten:

- Khong dat ten trung voi til khoa,

- Trong cung mot pham vi va cung thoi gian ton tai khong duoc phep d~t hai

ten trung nhau. C6 nghia la, trong cung mot kh6i l~nh (xem muc 1.2.5) khong duoc phep khai baa hai ten trung nhau,

- Ten phai phan anh duoc ban chat cua d6i nrong diroc d~t ten. Vi du khi khai bao mot bien dung d~ chua kieh thiroc cua mot mang ta nen dung ArraySize d~ nhan rnanh thay VI dung arraysize hose mot ten hoan toan khong goi nho nhu as ...

- Co nhieu quy uoc d~t ten khac nhau, vi du nhu cac lap trinh vien ella MicmSoft Windows va OS/2 thl thuong d~t ten thea .cach viet kie'u Hungary". Theo each viet nay moi ten phai diroc ghi them dang truce mot tien t6 phan biet kieu va pham vi cua bien d6. Vi du, mot bien toan cue ki~u s6 nguyen dung de chua

7

kich thtroc cua mot rnang co th~ viet nhir sau: giArraySize (g viet tiit eua global, i vie't tiit cua integer). Theo each viet nay chuang trinh tra nen tuong d6i sang sua, tuy nhien voi cac kieu dfr lieu tu xay dung thl each viet nay to ra tirong d6i kh6 sir dung, Trang giao trinh nay, chung toi quy uOc d~t ten nhu saii: moi ten chung, toan Cl;IC (1I11lt tell ham, ten cdu true ... ) diroc viet bang ca hai kieu chir. bit dau bang mot chir g (viet tar cUa global), cac til se phan tach nhau boi kf tl! hoa, MQi ten dia phuong cua ham diroc viet bang ca hai kieu chu, cac til ciing phan tach nhau boi lei nr hoa. Cac hang s6 diroc viet bang chir in. Cac hang ki~u enum dtroc viet bang cit hai ki~u chit

- DQ dai t6i da mac dinh cua mot ten trong ngon ngfr lap trlnh C la 32, tuy , nhien ta c6 the thay d6i lai bang mot gia tri tir 1 den 32 trong Option-c-Compiler=> Source-s-Identifier. Neu gia tri nay vuot qua 32 thl chi 32 kf nr dau tien duoc diroc chap nhan.

1.2.4. Ki~u an lieu

1. Cac kilu du lieu co san

Turbo C dinh nghia san 4 kieu dfr lieu co ban do Ill: char, int, float va double. Chung duoc rno ta chi tiet trong bang sau:

Bang 1.2. Cac kieu dir lieu trong ngon ngir l.\ip trinh C

Kie'u Mota Pham vi bi~u dien Kich thuoc
char Kieu ki tv -128 den 127 1 byte
in! Kieu s6 nguyen -32768 den 32767 2 bytes
float Kieu so rhuc dsu phay ±3.4E-38 Mn ± 3.4E+38 4 bytes
dong dg chtnh xac don
double Kieu so thuc diu phay ±1.7E-308 den ± I.7E+308 8 bytes
dong dQ chfnh xac kep Mt)t s()' diem can luu j:

- S6 thirc ki~ufloat CO de:) ehinh xac la 6 chu s6 san dliU cham thap phan, con s6 thirc kitiu double CO d¢ chinh xac la 15 chir so sau dau cham thap phan, do v.\iy khi su dung neu yeu can gia tri Ian. d¢ chfnh xac cao thl nen dung double, ngiroc lai chi nen dungfloat.

- Moi kieu du lieu CO ban tren Iai CO th~ ket hop voi mot hoac nhieu "ti~n t6" sau day: short, long. signed (/lg6m dint: dOl vai char vii int) va unsigned, M thay d6! pham v bitiu dien cua mlli ki~u du lieu do. M¢t s6 ki~u ket h<JP thong dung co the diroc mo tii. thong qua bang sau:

Bang 1.3. Mot s6 kieu dfr lieu thong dung co su dung them [;ell t6' trong C

Ki~u dft Ii~u Pham vi bi~u dil~n Kleh IhU'ac
unsigned char o den 255 1 byte
unsigned int hay unsigned Od€n 65535 2 bytes
short int -32 768 d€n 32 767 2 bytes
long int hay long -2147483648 den 2147483647 4 bytes
unsigned long int hay o den 4294967295 4 bytes
unsigned long
long double ±3.4E-4932 Mn ± l.lE+4932 10 bytes 8

2. Kilu enum

Ki€;u enum trong ngon ngtr lap trinh C la mot loai kieu liet ke dung de khai baa cac bien chua cac d6i nrong kieu dern dircc co gin tri thuoc mot mien tlur til dtroc chi r6 trong hie khai bao. D~ tao ra mot dG' lieu kicu enum ta sir dung cau lenh c6 cu phap sau day:

enum ten_kieu {danh sach cac phan tli};

Trong d6 ten kieu la len cua kieu du lieu lict ke moi vira diroc t<:LO ra, danh sikh cdc phdn tilla cac gia tri liet ke rna cac bien co Iht nhan duoc, cac phan ni phan each nhau boi dau phay.

Vi du I-L, De Hun viec voi cac ngay trong 'min ta eo the dung kieu WeekDay nlur sau:

enum WeekDay {SUNDAY, MONDAY. TUESDAY, WEDSDAY, THURSDAY, FRIDAY, SATURDAY} Oay1;

enum WeekDay Oay2;

Khi d6 Dayl va Day2 la cac bien kieu WeekDay va cluing c6 th~ nhan cac

gin tri da diroc liet ke. Cac cau lenh sau day la hop I¢-:

Oay1 = SUNDAY; Oay2 = FRIDAY;

Thirc chat cac bien kieu enum trong ngon ngu l~p trinh C diroc coi la cac bien nguyen, chung duoc cap phat 2 bytes bo nho va c6 tM nhan mot gia tri nguyen nao d6. M6i khi mot du lieu kieu enum duoc dinh nghia ra thi cac phan tir trong danh stich cae phein til sc duoc gan cho cac gia tri nguyen lien tiep hit dau nr O. Vi du nhu kieu WeekDay a tren thi SUNDAY se co gia tri 0, MONDAY se c6 gia tri 1 ... Do d6 hai cau lenh sau day e6 ket qua gi6ng nhau:

Dayl = 0; va Day} = SUNDAY;

3. Ctu: ki.e'u It! d!nh nghia

Trang ngon ngu l~p trinh C ta eo th~ It! dinh nghia ra cac kieu du lieu ella rieng minh bang each them tir khoa typedef vao tnroc mot khai bao nao d6.

Vi d~ 1-2. Dinh nghia kitiu bang typede].

D~ khai baa mot bien nguyen co ten lit nguyen ta eo th~ viet nhu sau: int nguyen;

Nhung neu ta them tir khoa typedef vso tnroc ella khai baa do: typedef int nguyen;

Thl hic nay nguyen dii trc thanh mot kieu diI lieu moi va cau lenh sau day la hoan toan dung: nguyen t.i : tUC1l1g nr ta ding e6 the dinh nghia ra mot kieu du lieu moi c6 ten lit MangNguyenSO dung de khai baa cac bien mang nguyen c6 kich thiroc la 50 nhu sau:

typedef int MangNguyen50[50};

9

Sau cau Ienh nay MangNguyenSO.se tra thanh mot kitiu dii lieu moi va ta c6 tM dung n6 d~ khai baa cho cac bien wang til nhu viec khai baa cho cac bien c6 kieu dinh san. CAu lenh sau se tao ra hai bien kieu MangNguyenSO 13.. ml va m2, moi bien se la mot mang kieu s6 nguyen co kich thUDC la 50:

MangNguyenSO m 1, m2;

1.2.5. Kh6i lenh

Khoi Ienh la mot day cac cau lenh narn trong khoi baa biJi dau "{"va dau "}",

Sau day 1a mot vi du. .

Vi du l-S, Cau true cua mot khoi lenh. {

/* Cac C8U I~nh narn 0 day*/ (1) int a;

a:::117;

}

Chit j:

1. Trang chuang trinh C, moi khoi lenh ve mat logic duqc xern nhu mot cau lenh rieng le, co nghia la trong chuang trinh, ell cho nao d~t diroc mot cau lenh thi ta cling co quyen d~t kh6i lenh vao do. Hi€u khong ro ve khoi Ienh Ia mot 16i thirong rat hay mac ph iii cua nhtrng ngiroi moi bilt dau hoc lap trinh. Trong ngon ngfr lap trlnh C cting nhu cac ngon ngfr lap trinh bac cao khac, co nhfrng cau true rna sau no chi diroc phep d~t mot cau lenh rna thoi, vi du nhu cau true if ... else, cau true/or, cau true while ... nhung thong thuong sau cac cau tnic nay ta can phai thirc hien lien tiep nhieu cau Ienh khac nhau moi dap trng diroc yeu cau. D~ giai quyet van de nay ta chi can dua tat cii cac cau lenh do vao trong mot khoi Ienh va hie nay ve mat logic chting se diroc xern nhu la mot lenh duy nhat. Neu ta khong dua vao trang khoi lenh se dAn den hoac chuang trinh chay sai, hoac se baa 16i.

2. Ben trong mot khoi lenh lai co th€ chua cac khoi lenh khac, SIJ long nhau nay la khong han che,

3. M6i than ham thuc chat la mot khoi lenh dung M baa cac khci Ienh khac

trong n6 (cac win de' vi ham se duoc trinh bay trong chuang 4).

1.2.6. Bien V3 cac 4~c trung cua bien

1. Khai niem:

Bien la vung nho diroc cap phat dung d~ hru tn! gia tri cho mot kieu diJ lieu nao do tai mot thai diem nhat dinh va no diroc truy xuat thong qua mot ten da: diroc khai baa cho bien do. Mot bien trong ngon ngir lap trlnh C tnroc khi diroc sir dung thi no ph iii duoc khai bao i:J ddu moi kh{/i l¢nh ttruac bat cit cau lenh' nao khac) thea cii phap chung nhtr sau:

Kii'u_du_li~u Ten_bien;

1 Trong ng6n ngii I~p trlnh C, tat ca cac cau d~l trong c~p dau /* '"I duoc eoi la nhttng chu thlch va diroc trlnh bien dich bo qua.

10

Trang do Kie'u_dff_li¢u se xac dinh kieu ella dii lieu rna bien luu trir.

Ten bien la mot dinh danh duoc gan eho vung nho chua bien va dung M rruy xuat giri ttj ella bien. Dau ";' d~ danh dau su ket thuc cua cau lenh. Vi du khi ta e6 khai baa sau day:

int SoVongLap;

thl khi bien dich may se cap eho (a mot khoang nho co d9 dai 2 bytes co ten la SoVongLap dung d~ hru tnt cac gia tri eho mot songuyen nao d6.

Trang mot dong lenh ta hoan roan co th6 khai baa nhieu bien cung kieu bang each phan tach cac bien do boi cac dau phily thea eli phap sau:

Ki~u_du_li~u Bien1, Bien2, ... , Bien_n ;

Vi du 1-4: CAu lenh float a, b, e=10, d: se khai baa fa 4 bien kieu so thirc a, b, e va d, trong do chi co duy nhat bien e duoc klufi gan giG. tri ban ddu la 10.

2. Dijc trung cua bien

VI tri khai bao cda bie'n: Day la d~e tnrng rat quan trong ella mot bien, n6 se xac dinh phf"!.m vi su dung va thtii gian ton tai cua bien d6 trang chuang trinh. Trong ngon ngO' l~p trlnh C phan biet hai loai vi tri khai bao eho bien, d6 la:

a) Neu bien diroc khai bao 0 ben ngoai cac kh6i lenh tnghia la a bell ngoai cac ham) thl n6 se duqc goi la bien ngoai hay con goi la bien toan cue, Pham vi sir dung tpham vi hoat d(Jng) cua no se c6 gia tri tir vi tri khai baa cho den het tep chuang trlnh. Nghia la n6 c6 the duqc truy xuat tir bat Cll ham nao bat dau tu vi tri khai baa cho den het tep chtrong trinh. Con thm gian ton tai (fhOi gian ducc cdp phdt bq nM) cua bien la su6t thai gian rna chuong trlnh lam viec, Nghia la gia tri cua bien (neu co) se duoc hru giii trong su6t thoi gian rna chuang trinh hoat dong. MQt bien ngoai co the duqc khOi gdn mt)t liin Ilk dich chuang trinh, neu khong duoc khoi gao may se mac dinh gan cho gia If! 0 hoac NULL (neu ia con trd).

b) Neu bien duoc khai bao ben trang mot khoi lenh (co nghia ia ben trong cdc ham) thl n6 ducc goi la bien trong hay con goi la bien cue bt) hoac bien tif dt)ng. Pham vi sir dung cua bien la ben trong kh6i lenh rna no duoc khai baa, nghia . 1a n6 chi c6 tM duoc truy xuat ben trang khci Ienh d6 rna thai. Con thoi gian ton tai cua bien (thai gian duac cap phat bq IIhit) la b~t dau tir khi may lam viec voi khoi lenh cho den khi ra khoi kh6i lenh d6. C6 nghia la khi fa khoi kh6i lenh, vung nho duoc cap phat cho bien se bi xoa, va do do cac gia tri ella bien cting se mat di. M9t bien trang tkhong tip dung cho mdng) nell khong duoc khoi gan mot gia tri nao d6 thi bien d6 hoan toan khong xac dinh (1111(111 mot gia tri ngau nhien san co trong b(j nha luc duoc cap phat).

Vi d~ 1-5. De hieu r6 hen, hay xet doan chuang trlnh sau day:

{ I*Kh6i I~nh 1~/ lnt a=10, b;

{ I*Kh6i I€mh 2~1 int a, e;

a=100; t: Goi bien a cua kh6i lenh 2*/ b= 1 000; 1* GQi bien b eu~ kh6i 'I~n h 1 ~ I

11

}

a=200; /* Goi bien a ella kh6i Jenh 1"/

e=1999; /* Sai do pharn vi ella bien e chi trong pharn vi kh6i I~nh 2*t

}

Doan clurong trinh gom co hai khci lenh long nhau, khoi lenh ngoai khai 00.0 hai bien nguyen a va b, khoi lenh trong khai baa hai bien nguyen a va c. Khi d6 lam the nao d€ phan bier dircc bien a a kh6i lenh trong va bien a a khoi lenh ngoai? Th,!C chat trong tnrong hop nay may se cap phat hai khoang nho khac nhau cho hai bien nay, pham vi hoat dong va thai gian ton tai ella chung cung khac nhau. Bien a 6 khoi lenh trong co pharn vi hoar dong tai cac cau lenh cua khoi Ienh trong va n6 chi ton tai trong thai gian may lam viec voi khoi Ienh nay, fa khoi khoi lenh trong bien a 6 khci lenh trong se bi xoa, Con pharn vi hoat dong cua bien a a khoi lenh ngoai bao gam cac cau lenh ben trong khoi lenh ngoai nhung khong thuoc kh6i lenh trong, viec thay d6i gia tri cua bien a a khoi lenh ngoai khong anh hirong gl den gia tri ella bien a 6 khoi lenh trong va ngiroc lai, Pham vi hoat dong cua bien b thi gam ca cac cau lenh cua kh6i lenh ngoai va khoi lenh trong (da khong co bien b a kh6il¢nh trang) va thai gian ton tai ella nola trong suot thai gian may lam viec voi hai khoi lenh nay. COn pharn vi hoat dong cua bien c chi baa gam trong cac Call Ienh thuoc khai lenh trong rna thoi, ra khoi khoi lenh trong bien c khong con ton tai ntta.

Loai bien: Moi bien sau khi khai bao con diroc d~c trung bai cac tir khoa di kern phia tnroc nhu static, auto, extern, register, const va volatile.

Tir khoa auto dung de chi r6 tinh CI,lC bo cua mot bien diroc khai bao ben

trong ham. VI cac bien nay duong nhien Ia CI,lC bQ cho nen tir khoa nay trang ngon . ngif Iap trinh C it diroc dung. Ttl khoa extern duoc S11 dung khi mot chuang trinh diroc viet tren nhieu tep, each S11 dung tir khoa nay se duoc trinh bay chi tiet trong phu luc I. Ttl khoa register dung M xac dinh mot bien CI,lC bo co tM diroc hru tnt trong cac thanh ghi SI hoac DI (2), khi cac thanh ghi nay ban thl cac bien nay diroc hru tnr nhtr cac bien cue bo khac, Do d6 bien register co the; diroc dung lam bien dieu khien de: tang toe do thirc hien cua cac Yang lap. Tir khoa volatile dung de bao cho Turbo C biet gia tri cua bien c6 thl1 bi thay deli thea mot each nao do khong diroc mo ta r5 trong chirong trinh va rhirong dtroc S11 dung trong lap trinh C nang cao, do d6 khong diroc de cap den trong giao trinh nay. MQt ttl khoa quan trong rna ta dn narn virng d6 la tir khoa static. Khi tir khoa static diroc dat tnroc mot khai bao cua bien ngoai thl ta co biln tinh ngoai, khi tir kh6a nay dat tnroc mot khai baa cua bien trong (bien Cl.}C b¢) thi ta c6 bien tfnh trong, Cii bien tinh trong va bien tinh ngoai deu co thai gian ton t~i la trong suot thai gian rna chuang trinh hoat dong, co nghia la no diroc cap phat bo nho tir khi chuang trlnh chay cho den khi ker tlnic chuang trinh va do d6 gia tri diroc hru gill trong cac bien do kh6ng mat di trong suot thai gian chirong trinh hoar dong. Tuy nhien, pham vi hoar dong cua bien tinh trong chi gioi han trong pham vi khoi Ienh rna n6 diroc khai bao, con pham vi hoat dong ella bien tinh ngoai dtroc tinh til khi khai bao cho den het tep chuang trlnh. Neu chuang trlnh chi viet tren mot tep thl pharn vi hoar dong cua bien tinh ngoai

! Thanh ghi co th~ hieu Iii. bQ nho dac biet ben trong bo vi x.u li,

12

va bien ngodi la nhu nhau. Ca bien tinh trong va bien tinh ngoai deu,'e<6 thti duoc khOi do;u mt)t Lin ltu: dicn chuang trinh. Neu khong se nhan gia tri 0 hoac NULL.

cna»

- Bien tinh ngoai khong th~ rna rong sang tep khac bang tir khoa ex/ern.

~ Neu mot bien ngoai duoc khai bao a dau chuang trmh (truce tat cd au: ham) thi n6 c6 th~ diroc sir dung ooi bat ki ham nao trong chuang trlnh voi dieu kien trong ham d6 khong c6 bien cue bo trung ten voi n6 diroc khai bao.

- Neu chuang trinh duqc viet tren nhieu tep va cac tep duoc dich doc lap thi pham vi sir dung cua bien ngoai eo th~ rna rong tir tep nay sang tep khac bang tir khoa extern ixem phu luc I).

1.2.7. Hang

1. Cdc loai hling

Haug la cac dai hrong rna gia tri cua n6 khong thay d6i trong qua trinh rhuc hien chuang trlnh. Trong ngon ngu lap trinh C c6 cac loai hang sau:

Hung nguyen

U. dai hrong co gia tri tir -32768 den 32767. C6 th~ bieu dien mot hang nguyen diroi dang thap phan, bat phan (CIY so' 8) hay thap luc phan (c(t ~'o' 16). Ngon ngfr lap trlnh C quy dinh bi~u dien mot so dirdi dang bat phan bang each them 0(50' khong) a dau, diroi dang thap luc phan bang each them Ox.

Vi du 1-6. Cac loai hang nguyen.

22913 m(lt hang nguyen h~ thap phan,

0345 la mot tang nguyen he bat phan, gia tri ella no trong he lOla 3*82+4*81+5*8°=:229.

OxA9 la mot hang nguyen he thap luc phan, gia tri ella no trang he lOla 10* 161+9* 16°=169.

Hling long

Giang nhu bang nguyen, khac 6 eh6 e6 them chit L hoac I a dang sau d~ bieu

thi d6 la hang e6 gia tri long. Vi du: 1981, 1234562L.

Mot bang sO nguyen VUQt ra ngoai pharn vi cho phep duqc ngam hi~u la hang long. Hling s{1 thuc

C6 hai each viet gia tri cua mot hang so thirc. Trang each viet thong thuong, hang diroc viet giong nhu trong thuc te nhung thay dau phay thap phan bang dau cham. Vi du 359.12, -415.16. Cach viet thir hai la theo ky phap khoa hoc, Theaeach viet nay hang duoc viet gorn hai phan: phan dinh tri co dang mm.nnn va phan mil phan tach voi phan dinh tri boi ki nr e hoac E.

V f du: 12.3 E + 3 gia tri ella hang nay bang 12.3 * 101= 12300.0; phan dinh tri (123) Ia so thirc; phan mii (+3) la so nguyen. Vi chting ta co the tang giam gia tri cua phan mil va tuang irng dich chuyen dau cham thap phan trong phan dinh tri nen so thuc duoc viet diroi dang nay con c6 ten goi la so thirc dau phay dong, con each viet tnroc d6 nrong ling vai ten goi so thirc dau phay tinh.

13

Chit j: Khi vi~t Mng dau phly tinh (dgng thdp phtin) thi pMu nguyen hay

phan thap phan co thS vdng m~t nhung dau chain khong duqc phep vdng m~t:

Vi du: .2~ hay 39. Hi cac hang dsu phay tinh.

Hdng ki tu

La mot ki ur rieng biet ducc di:lt giira hai dau nhay don, vi du 'A', 'b '. Gia tri cua hang kf tI.! chfnh la rna ASCII cua ki tu do (3).

Vi du: Hang ki tu 'A' c6 gia tri 65, hang ki nr /d' e6 gia tri 100.

Hang kf nr ve thuc chat co the coi no nhu mot gia tri nguyen. Do d6 n6 cling co th~ tharn gia vao cac phep toan s6 hoc nhu moi s6 nguyen khac, Vi du ta c6 th~ vi€t: 'a '_ 'A' bieu thirc nay thirc chat la 97- 65 = 32 = ' '(ki tu (Tong).

Hang kf nr con e6 the dtroc viet In U-iX;>X;', trong d6 Xi. X2, X; la cac chfi s6

cua he dern CO" s6 8 rna gia tr] cua XjX;>XJ tang rna ASCII cira kf nr d6.

Vi du '\142' lit bang ki nr 'b ', '\101' la hang ki til 'A '.

C6 mot s6 hang kf nr dac bier dtroc vi€t theo guy iroc trong bang sau:

Bang 1.4. Qu y uac viet mot s6 kf nr di:lc bier trong ngon ngtt lap trmh C

Viet Ki tl! Dien giai
'\' , , Dau nhay don
'\, ' Dau ph~y
~ \" , " Dan nhay kep
· \\' \ Dffu gach cheo ngu:qc
'\n ' \n Ki n.r xu6ng dong
· \D' \D KitlrNULL
· \J ' Tab Kitl_rTab
'\b' Backspace Ki ur Backspace
'\r ' f:R Ki tl.f!ra ve Jau dong H ling xdu ki tu

La mot day ki nr dtroc d<)t tr ong cap dau nhay kep " ".

Vi du:

"Thanh ph6 H6 Chi Minh", "Wellcome to Hanoi", "" (xdu rang), .. Xau ki ur diroc hru trfr trong may dum dang mot mang ki~u char, Trinh bien dich se tlJ dong them ki nr NULL (ki tu '\01 vao cu6i moi xau de danh dau su k€t thuc cua mot xau,

csa «

an phan bier gitra ki nr 'd' va xau "d". 'd' 1.1 hang ki 11.J ducc hru trtr trong mot byte con "d" Ia mot xau kf nr duoc luu rrtr trong mot mang gam hOO phan tir Iii 'd'va VJ',

2. Ten hling va bien hling

Bien hang la mQI Ioai bien rna gia tri cua n6 khong th~ thay d6i trong hie chay chuong trinh (4). COn ten hang la mot loai hang duoc dinh nghia bang chi thi itdefine.

3 Bang maASCl/ Iii bang rna chuan dung M rna hoa cho cac kf nr, Xem phu luc IV.

14

a) Ten hang

Duoc dinh nghia thea mot trong hai cu phap sau: #define <Ten> <Gia trl>

#define Ten{Oanh_sach_doi) Bieu_thue

Cau true thu nhat dinh nghia mot len hang eo ten la Ten e6 gia tri la Gia tri.

Gia tri (; day co th~ lit mot day ki nr, mot gia tri s6, mot ten ham ... Khi bien dich, chuang trinh dich se thay the cac hin xuat hierr cua Ten bang Gia _Iri nrong (rug eta duoc dinh nghia,

Vi du 1-7. X6t doan chirong trinh sau: #define begin {

#deline end}

#define MAX 20000

#aeTine chxh "Conq hoa xa hoi chu nghia Viet Nam" #define in printf

int main{)

begin

in("\nChuoi dinh nghia la: %s", chxh); in(~\n Gia tri Max= %d", MAX);

return 0;

end

Khi bien dich ham main() dtrqc thay the nhu sau: int mainO

{

printW\nChuoi dinh nghia la: %s~,HCong hoa xa hoi chu nghia Viet\ ($) Nam"):

printf("\n Gia tri Max= %d", 20000); return 0;

}

Chl1C1Ilg trinh bien dich se thay the cac ten hang begin, end, MAX, chxh, in bang gia tri diroc dinh nghia tUC1Dg ling la '{'. '}'. 20000. "C ong hoa xa hoi c hu nghia Viet Nam" va printf.

Cau true thu hai dung de dinh nghia cac Macro cho chuang trinh. Vi du ta co the dinh nghia ra mot Macro dung de tfnh dien tich cua mot hinh chir nhat co hai canh tUC1Dg tmg lit A va B nhir sau:

Vi dlf 1·8. Viet Macro tfnh dien tlch hinh chir nhat. #include "stdio.h"

#define DienTich(A,B) (A)*(B) int malru)

4 Bien hang hay diroc sir dung khi trong chuang trlnh ta can den cac bien rna gia tri ella no khong the bi thay d6i trong su6t thai gian chuang trlnh hoat dong.

STrong ngon ngir I~p trlnh C. de viet mot chuoi k[ tt! trong dau " .. tren nhieu dong thl phai dij.t dau '\' vao eu6i dong tnroc do.

15

{

int a=10, b=20; float e=30, d=4;

printf{"Dien tich eua hinh chu nhat co eanh a, b la: %d", DienTieh(a, bj): printf("Dien tieh eua hinh ehu nhat co eanh e, d la: %.2f', DienTieh(e, d)); return 0;

}

Khi bien dich, trinh bien dich se (hay-the cac cau lenh:

Dienl ichta, h); thanh a*h va Dieul ichtc, d): thanh c*d va ta eo ket qua dung cua dien tfch cac hinh chir nhat do.

Chily:

- M9t dinh nghia dai co the' dlCQ'C tiep tuc a dong sal! hang each di!-t dau '\' vao cuoi ella dong tnroc.

- Pharn vi ella bien hang diroc dinh nghia boi iidefine la tir khi no dtroc dinh nghia cho den cuoi tep g6c. Tuy nhien mot bien hang Tell cling co the' diroc dinh nghia lai sau cau lenh #lIl1def Tell.

- Phep thay the khong thirc hien cho cac hang chuoi kf nr. Vi du nhu ten hang chxh da duoc dinh nghia a tren nhirng neu no diroc dat trang hang xau ki t\T sau "Toi noi chxh 1'01 moi nguoi" thl chxli trang xau nay khong thf diroc thay the bang gia tri da diroc dinh nghia.

- Khi dinh nghia cac Macra bang #define can hru )' Iii. phai luon dat cac doi so cua Bieu fhuc trong cap dau ngoac ( ). Vi du ta XCI lai Macro dung de' tinh dien nch ella mot hlnh chir nhat da: co 6 tren, nell ta viet lai nhu sau:

#define DienTich(A, B) A*B

thl khi gap Call Ienh sau:

Die nl' i clu I 0+8,7); trlnh lien dich se tha y the bang bie' u thirc 1 () + 8* 7 do do ket qua se bi sai. Nhung nell ta Vil't lai la :

#define DienTich(A, B) (A)"B) khi thirc hien ta se nhan diroc ket qua Ill: (10+8)*(7) va luc nay chuang trlnh cho ket qua dung.

b) Bien hang

Diroc dinh nghia bang tir khoa const voi cu phap nhu sau:

const Kieu TenBienHang = gia_trl; Vi du 1-9. each khai baa cho bien hang. const int MAXUN E = 100;

canst char NEWLINE = '\n';

canst char DHBK[18] = "DAI HOC BACH KHOA";

V e mat y nghia, cac cau lenh bat dau bang CO list xac dinh mot bien eo gia tri khong thay d6i (birtH hang). Nghia la moi eo gang nham thay d6i gia tri ella cac bien nay sau khi khai bao deu khong hop I¢ va gay ra 16i bien dich,

16

1.2.8. Cau I~nh

CAu lenh lit dan vi nho nhat cua mot chuang trlnh may tinh, co nghia 1a tat cit cac chuong trlnh deu phai duoc xay dung len tu ~p h<;1P cac CAll Ienh theo mot thir nr logic nao da:y. M6i ngon ngil' I~p trlnh se quy uOc vitt cac CAll lenh khac nhau. Trong ngon ngil I*p trinh C m6i cau lenh phai dUQ"c ktt thuc bang mot dau " ; "

- (ngoai Irll cac chi Illi li!n XU Ii nJII( #define, ttinclude ... ) va chung c6 tht dUQ"C viet tren mot hose nhieu dong. Tuy nhien khi viet cac cau lenh tren nhieu dong can phai tuan thea m¢t s6 quy lAc nba:t dinh,

Quy tiic viet m~t' eau ~nh: Gifra cac tu trong m¢t CAll I¢nh co the d~t rnor hoac mot s6 cac dau each ' , hoac dau xu6ng dong (ki II{ '\n ). Dieu nay co nghia III ta khOng dttqc phep be gay mot tu tren nhieu dong hoac lam gian doan mot tit hOi dau each,

Tu III met day kf tt! viet lien nhau mang mot y nghia nhat dinh, Trong ngon

ngil' lap tr1nh C co cac loai tit sau day:

a) Cae hilng. Vi dl,J 'K', ~100.00, "'Hello!"

b) CSc ten. Vi dl,J Hoenvi, DienTieh ... e) Clic titkhoa. Vi dl,J for, if, else ...

d) Cae diu philp tfnh. VI dl,J (, &, ++, ~~, == ...

e) Mpt ~6 diu ehUc nang. VI du ;, j, : ...

Sau day III mot s6 vi du ve each viet cua cac cau lenh. Vi dIJ.1·10. each viet mot cau lenh,

S + = a; r Sai vi += la m¢t tit, do do khOng dllQc phep d~t d~u each vao gilla"l

for ( i=O ; i< r £)ung VI cac W v~m dam bao tfnh Him tuc cua cac ter!

2: ++

i);

dou

ble x=200.0, y=299.23; printf("\n x= % 1 O.2f

v= %10.2r, x,y);

Chuj:

- D6i voi cau Ienh #include (6) va tidefine, quy tac n6i tren khong hoan toan dung, gitra dau #, tir khoa include va ten tep c6 th~ d~t mot s6 bat kl khoang each nhung phai tren mot dong. Tirong nr voi #de{lne.

- V oi mot hang xau, ta c6 th~ viet tren nhieu dong khac nhau nhung phai them mot dA'u '\' vao cuoi dong tnroc,

1.2.9. Vao / r'a

I"Sai vi nr khoa double bi be gay·'

r thanh hai dong, ht.ng xau trong "f

'*Sai vi hang xau b] be thanh hai dong"l

v 00 I ra ia cac thao tac co ban de giao tiep gitra may tfnh voi the gioi ben ngoai (cac thilt hi ngoai vi). Cac thiet bi ngoai vi thi rat da dang va phat tri~n khong ngirng, cho nen mot trong nhiing huong di cho van de nay la tao ra cac giao

6 Chi thi nay se duoc giai thieu trong muc l.3.

,.02-GTNNLTC

17

dien khong phu thuoc phan cirng inhu co cht may do trong Java). Trong ngon ngir lap trtnh C, de tao ra co che' vao / ra mem deo ngiroi ta khong trao dOi dfr lieu true tiep giUa chuang trinh voi cac thiet bi ngoai vi rna thong qua cac kenh trung giant cac kenh nay dtroc xern nhu la cac thiet hi logic va diroc goi la cac dong xuat nhdp, Cac dong xudt nhap thirc chat la cac vung dern duoc gan tuong img voi cac thiet bi vat li thirc su va cluing duoc nr dong rna moi khi moi tnrong ket hop Turbo C ho .... t dong (xem them chuang 5, muc 5.3.3 phtu: 4 d€ IlIlu r6 hem van de'IUiy). Viec trao d6i dir lieu giira chuang trinh va cac Ihiel bi dien ra thuc chat d6 Ia SlJ trao ddi gitta chuang trinh VOl cac vung dern va cac vung dem voi cac thiet bi thuc su, Ngon ngir l~p trinh C dinh nghia ra cac thief hi logic chuan sau: stdin (thilt hi vao chudn - him phimi, stdout tthie: hi ra cliudn - man hinlt), stderr (thief bi l6i chudn - man hinh) va stdprn (thief hi ill chuan - may ill).

Thao tac )'00 / ra co ban diroc xet trang muc nay la thao tac xuat ra man hlnh va nhap vao tir ban phim. Ngon ngtr lap trinh C eung cap cac ham thu vien nrong doi tien dung eho viec xuat nhap lam viec theo ca hai kieu la khong thong qua cac dong xuat nhap va thong qua cac dong xuat nhap.

, 1. [Jam print!

U. ham ra chuan diroc khai baa trang tep tieu de stdio.h ella Turbo C dung d~ trinh bay dfr lieu ra man hinh thea mot khuon d a ng nao d6 do nguoi viet chirong trinh dinh ra thong qua dong xuar chuan stdout. D a ng tong quat ella ham nhu sau:

int printf(eonst char *DieuKhien [,DanhSaehCacDoi]);

Trang d6 Dieulshien la mot hang can tro (7) kieu char chua dia chi cua chuoi dieu khien. Chuoi dieu khien I a i e6 th~ baa g6m ba lo .... i kf nr sau day:

a) Cac ki tu dUu khi€n: D6 Hi cac ki til e6 rna tir 0 den 31 va ki nr e6 rna 127 (ki tu DEL) trang bang rna ASCll. Moi khi mot kf nr dieu khien xuat hien trong chuoi dieu khien thi chirc nang dieu khien ella ki nr d6 SI! diroc thirc hien, VI du neu ta viet prim/( "\11 "); thl con tro man hinh SI! diroc chuyen den dau dong tiep thea (kf tu In . fa ki (if dijc biet cho trong hdng 1.4).

b) Cac ki tl! hiln thi: D6 la cac ki tlJ eon lai trong bang rna (lIly nhien cdc ki tu co rna ft~ 128 din 255 ta cdc ki t« d6 11Ot;l khong co tren ban phim) se diroc hien thi ra man hinh rnai khi ham duoc goi, Vi du d~ hien thi chuoi "Hello!" ra man hinh ta c6 th6 viet lenh printft "Hello! "); . Ngoai cac ki tu hien thi thong thuong, trang ngon ngfr lap trinh C c6 dung mot s6 ki nr nhu '\' , ", (dau nhdy dan), ': (dd'u phdy), ' ", (dau liMy kip) ... d~ bieu dien cho cac cu phap rieng cua ngon ngfr. Do do, M hien thi diroc cluing ra man hlnh chung ta can viet nhir sau:

printf(" \' "); se in ra dau ' printf(" \" "); se in ra dau " printf(" \\ H); se in ra dau \ printf(" . "): se in ra dau , .

7 Bien con tro se diroc de cap den trong chuong 3, muc 3.3.1.

18

c) C6c d4c td: DUng d~ dua du lieu fa man hlnh theo mot khuon dang nhat dinh (dtr lieu nay se nam trong DanhSachCacDoi). M6i dac ill co call tnic tong quat nhtr sau:

%[-J[fw][.pp] KyTuChuyenDang 18)

Trang do dau % Ia de chi fa rang day la bat dau ella mot dfic fd chrr khong phai 1a kf nr hi~n thi hay dieu khien. Twang 'fw' Ia mot s6 nguyen xac dinh dl) rong t6i da cua twang fa. Khi fw Ian han dl) dai thuc t€ cua tnrong fa, thi cac vi tri du thira se diroc }{(p day boi cac khoang tr6ng hoac sa 0 (neu s6' ddu tien trongfw ld 0) va noi dung ella truong fa se diroc dAy ve ben phai (ni'u khong c6 mdt ddu -, ') hoac ve ben trai (ntu co mat ddu '- '), Khi khong e6 m<)tfw hoac khifw nho han hay bang d¢ dai thuc t€ cua tnrong ra thl do rong ella tnrong ra se bang do rong thirc teo

'pp' la mot s6 nguyen diroc sir dung khi d6i luang irng Ia mot xau kf nr hoac mot gia tri kieufloat hay double. Neu d6i nrong irng la mot s6 thirc thl 'pp' Ia d¢ chinh xac sau dau phay ella tnrong ra. Khi yang mat 'pp' trong tnrong hop nay thl d¢ chfnh xac dtroc mac dinh la 6. Khi d6i nrong trng la mot xau ki nr thi chi e6 'pp'

ki nr dau tien ella xau duoc hien thi neu 'pp' nho han d(l dai ella xau, '

Sau day lit mot vi du minh hoa eho nhirng dieu da noi i:J tren tchu y, dq dai truang ra duac dfit trong cap ddu ': : ').

Vi du l-Ll: Ket qua in ra man hinh nrong ling voi cac gia tri euafw va pp

Gia tri can hilin thi fw diu - .pp kel qua in ra
-2100 lO CO Khong :-2100 :
-2100 OlD CO KhOng :-2100 :
-2100 10 Kh6ng Kh6ng -2100:
-2100 OlO Kh01!K Kh6n_g_ : 00000-2100:
"abcdef" OlD CO KhCmg .abcdef
"abcdef' OlD Khong Khong : abcdef:
"abcdef" lO KhOng KhOng : abcdef:
"abcdef" 3 CO Kh6ng :abcdef:
"abcdef" 3 KhOng Kh6ng :abcdef:
123456 4 CO KhOn_g :123456:
123456 4 KhOng Kh6ng :123456:
-123.456 lO CO 2 :-123.46 :
-123.456 lO CO 0 :-123 :
-123.456 8 CO KhOng :-123.456000:
-123.456 10 Kh6ng 2 : -123.46:
"abcdefg_hi" lO CO 3 :abc :
"abc defg hi" lO Khong 6 : abcdef:
"abcdefghi" Khong Khong KhMg .abcdefghi:
"abcdefghi" 10 Kh6ng KhOng abcdefghi: KyTuChuyenDang 1a mot hoac mot day ki hieu, no xac dinh qlly tac chuyen dang cua gia tri can hien thi, M6i kiiu dii li¢u dell e6 mot ki tu chuytn dang cho rieng no, Cac ki tu chuyen dang trong ngon ngu lap trinh C diroc eho trong bang diroi day,

g Quy HOC ding, ta't ca nhtrng gl viet trong cap d[\u [] thl co th<i co mat hoac vang mar.

19

Bang 1.5. Cac ki nr chuyen dang cho ham print]

Ki III Kieu cua ghi tr] each chuyen dang
chuyen dang can hien thi
d hoac i int Girl tri can hien thi duoc coi Ii\. s6 nguyen he l O c6 dau,
Id hoac Ii long Gia tri can hien thi ducc coi lit so nguyen dai he 10 co dau,
a int Gia tri can hien thi diroc coi la s6 nguyen he 8 khong dau.
10 long Gia tri can hien thi diroc coi Ii\. so nguyen dill h¢ 8 khl'mg dau.
u int Gia tri can hien ttl! duuc coi lit so nguyen h¢ 10 khong dau,
Xhoac x int Girl tri can hien thi dtroc coi Ii\. so nguyen he 16 khong dllu
(neu Iii X thl se duoc hien fa duci dang_ chu hoa),
Ix long Oia tri can hien til! duoc coi lit s6 nguyen dill b¢ 16 kbong dlIu.
Gia tri can hien thi duoc coi lit s6f1.hl,fc vii. duqc hien th]
e,E float. double duoi dang kf phap khoa h9C (dang mu) voi dO dAi phan thap
phan co gia tri lit pp.
f float. double Gia tri can hien thi duoc coi hl. so thuc va duoc hien th]
duai dang s6 th~p phan dau phily tTnh.
Gia tr] can hien thi diroc chuyen sang dang s6 tMp phan
g,G float. double dau phay tinh hay dong tuy thuoc vao lor,ti nao ngiin hon.
Khong in ra cac so khong vo nghia,
c char Gia tri can hien thi duoc coi la mOt kf ur,
s char * Gia tri can hien thi duoc coi Iii. ffi¢t xau kf t\!. DanhSachCacDoi c6 tM; chua cac gia trj (cae hOng), cac bien hay cae bilu thuc (9) mu6n hien thi ra man hlnh. M6i deli so' (gia trio biEn hojJcbilu tlltlc) duqc phan tach nhau bOi mot dau phay, M6i khi thuc hien lenh, gia tri cua dOl sb~ nrong irng (10) (rfnll thea fllu tu til fred qua phdi) se duoc chuyln dang va hi~n thi ra man hlnh theo d~lc td tuang ung (ciIng tinh thea thtt tu til trdi qua phdi). Nhiing d6i nao khong c6 dac ta tuang img se khong duqc in ra.

Vi d':lI-12. Dira dit lieu ra man hlnh c6 su dung d~c ta. int a=10, b=20;

float e= 1.2: i '\

printWCae gia tri la:\nA=%d\nB=%d",a,b,c);

L_)

Neu cac cau lenh tren diroc thirc hien se cho ket qua nhu sau:

Cae gia tri la:

A=10 B=20

Bien c khong c6 dac ta cho nen khong duoc in ra.

Sau day la mot vi du minh hoa cho each dung ham printft).

Vi du 1-13. Lap trinh in ra man hlnh mot danh sach lap g6m 4 cot IAn hrot la Ho va Ten, Ngay Sinh, So hieu SV va Diem TBT sao cho cot Ho va Ten co do rong 13, 25 k( nr, cac ten can theo Ie trai, CQt Ngay Sinh c6 d¢ rong la J 5 ki tu, dit lieu can theo Ie phai, Cot So hieu SV co d¢ rong la 15 ki nr, dO' lieu can theo Ie phai, Cot

9 Bieu thuc se duoc d€ cap den trong chuang 2.

]0 Neu d6i s6 Ii mot bieu tlurc thl gia tri cua bieu thirc se duoc tfnh huck. sau do gia tri nay moi diroc chuyen dang thea d~e ta nrong ung va hien thi ra man hinh.

20

Diem TlJI' codo rong la 15 ki tu, dtr lieu can theo Ie phai va co do chinh xac la 2 s6 sau dau thap phan,

1* ************************~***********************************~************~********~****** *1

#include "stdio.h" #include "conio.h"

int mainO {

printW\n\n\n\t\t\tDANH SACH SINH VIEN\n\n\n"); printW%-25s%15s%15s%15s\n\n","Ho va Ten" • "Ngay Sinh" • "So hieu SV" • "Diem TBr);

printf("\n%-25s%15d%15s%15.2f" , "Nguyen Van A",leBK2003 A120", 6.246); printf("\n%-25s%15d%15s%15.2f" , "Nguyen Van B",13,"BK2003 A121", 7.146); printf("\n%-25s% 15d% 15s% 15.2f" , "Nguyen Van C" ,21 ,"BK2003 A 122", 8.2); printf("\n%-25s%15d%15s%15.2f" , "Nguyen Van D",18,"BK2003 A123", 5.125); printf("\n%-25s%15d%15s%15.2f" , "Nguyen Van E",15,"BK2003 A124", 4.925); getchO;

return 0;

}

I*~*****·****·***********~*******~**···***********************************************-**** */

Kit qua ch{lY chuang trinh:

DANH SACH SINH VIEN

Ho va Ten

NgaySinh

So hieu SV

DiemTBT

Nguyen Van A Ngu'yenVart B Nguyen Van C Nguyen Van D Nguyen Van E

11 13 21 18 15

BK2003A120 BK2003A121 BK2003A122 BK2003A123 BK2003A124

6.25 7.15 8.20 5.13 4.93

1* *.*************************~*****************************~**************~*.**~.********** */

Chuj:

- Neu mot d~c ta viet khong dung cau true (Ilghra id khong bat ddu bang ki tu % hoijc khong kit thuc bang mtlt ki tu chuyen dang) thi tflt ca cac ki tu d6 se diroc coi la kf nr hien thi va se duoc hien fa man hinh, Vi du printft "X= %h ",x); thl ket qua chay se la: x=%h.

- Giira chuoi dieu khien va danh sach cac d6i s6 phai diroc phan tach nhau bci mot dau phAy. Sau day la mot vi du sai ve ham pri Iltf():

printf("Toi noi rang\n%-20s" "Hello World");

Vi "Hello World" la mot d6i s6 can hien thi do do no phai duoc phan biet voi chuoi dieu khien "Toi noi fang\n%-20s" boi mot dau phay, ta viet lai nhu sau:

printf("Toi noi rang\n%-20s","Helio WorldM);

21

- De hi~n thi fa man hinh cac kf nr do hoa (khOng co mijt tren him phim) thi ta ph8.i sir dung rna ASCII cua de ki tu d6 trong ham printfi}. Vi d1,1. dt hien thi lei tt,t '(.'. ra man hinh ta phai vi~t: printf( "%e ", 128); gia tri 128 ebiob la rna ASCII ella lei nr '(:" trong bing rna.

- Neu sir dung sai lei U! chuyen dang thi se dan Mn ket qua hilin th~ sai.

- Moi d6i s6 can in ra ph.h e6 mot dac tA rieng cho n6.

- Ham printfi) se tra ve s6 ki nr diroc dua ra man hinh neu thanh cong (bao

g6m cd kf tu die'u khi€n). khi c610i ham tra ve gia tri -I.

Vi dr,lI-14. Gia tri tra ve ella ham print]. Xet doan cmrcng trmh sau: int a=30, b=3265, m:

m=printW\nA=%4d B=%d", a, b);

Thi m se e6 gia tri Ia 14.

2. Hilm scan!

La bam vao chuan diroc khai bao trong thu vien stdio.h dung M nhap dir lieu tir ban phim thea mot khuon dang xac dinh thong qua dong nhap chuan stdin rei luu tru cac gia tri da chuyen d6i d6 vao bo nho tai cac dia chi tirong U'ng trong DanhSachDoi. Dang t6ng quit ella bam nhu sau:

int scanf(const char *DieuKhien L DanhSachDoi]);

Trong d6 DieuKhien Ill. mot hang can tro ki~u char chua dia chi cua ehu6i dieu khien, Con Danksachlroi Ia danh sach dia chi ella cac bien dung d~ luu trif gia tri doc VaG tir ban phfm. Cac defi 56' (cdc gia tri dja chi ella cdc bii'll) can duoc phan tach nhau boi mot dau phay. Dt lAy diroc dia chi ella mot bien ta dung toan tir '&' dtrng tnroc ten bien d6. Vi du M lay dia chi cua bien x ta vi€t &x.

Chu6i dieu khien ella ham scanfi) thuong chi baa gom cdc aif,c td cho viec chuyen dang du lieu (khong co ki tI! die'u khiin hay ki tlf hie'n thi). Moi d~e ta se duoc wang U'ng voi mot dia chi cua bien. xac dinh nr trai qua phai, Bien nao khong c6 dac ta eho n6 thi se khOng dl1qc nhap gia tri, M6i dac ta cho ham scanft} e6 the diroc mo ta tong quat nhu sau:

%M[dd]KyTuChuyenDang

Trong d6 k{ h! % la dau hieu de chi ra su bat dau cua mot dac tao Ki tu ,*, khi c6 mat se cho phep dong vao van duoc do doc blnh thirong nhung gia tri nrong Ung doc diroc bi bo qua (klu)lIg duac luu VaG Cae bien n/uj) do do se khong c6 cac d6i tuong tmg (xem vi du 1-16).

Dbn~ V~? a ~ay _dt1Q'C h~fU !a milt, day ki tl,T li~~ t!ep nhap tir b~n phim da duoc chuyen toi stdin va k€t thue bang phim Enter. MOl dong vao baa gom m¢t hay

nhieu trllilng vao d6 HI. mot day ki t1,1 lien tiep nhau khong chua dau each, dAu Tat hoac ki tl,T xu6ng dong. Cac tnrong VaG c6 th$ duoc phan tach nhau boi mot ha) nhieu dau each, dau Tab hay dau xuong dong. Moi truong vao se duqc xet tuon! irng cho mot d6i s6 trong DallhSachDoi (theo thu tlf tl~ trai qua phdi). Vi du xe

dong VaG sau day: .

1234 abc xyz

456 Ghy (Enter)

22

se g6m co 5 tnrong vao d6 Hi 1234, abc, xyz, 456 va Ghy.

Tnrong dd trong d~c ta la mot gia tri nguyen xac dinh chieu dai cue dai ciia truang VQ:O se duoc doc eho d6i nrong irng. Neu dd vang m~t boac neu gia trj cua no 1&:1 han hay bang d¢ dai cua tnrong van nrong nng thl toan b¢ tnrong vao d6 se duoc doc va chuye'n dang thea d~c ta luang img cho n6, sau d6 gia tri nay moi duqe luu van bien tuang irng c6 dia chi trong DanhSachDoi (neu khong co ddu * dUf/c chi dinh). Neu gia tri ciia dd nho han de? dai cua tnrong van nrong ling thi chi phan da.u cua tnrong van e6 kich co dung bang dd duoc dQC va chuye'n dang sau d6 luu van bien urong ling. Phan con lai cua tnrong van se duoc gan eho cac deli tiep theo.

KyTuChuyenDang se xac dinh each thirc do doc cac kl nr tren dong van ding nhir phuong phap chuyen dang thong tin doc duqe truck khi gan n6 cho cac bien nrong mg. Danh sach cac ki nr chuyen dang diroc cho trong bang sau:

Bang 1.6. Cac ki tu chuyen dang cho bam scan!

Ky tu dac til Mu tii chtrc nang
i.d Nhap vao mQI so nguyen: doi so luang rmg phai Iii con Ira nguyen hoac
diu chi cua mot bien nguyen. Truong vao phai Iii mQI so nguyen.
li.ld Nhnp vao mot so nguyen dai; doi so wang ung phai [iI. con Ira kicu long
hoac lu dia chi cua mot bi~n long. Truong vao phai Iii mot so nguyen.
Nhap vao mQI so nguyen he 8; doi so luang trng phiii la con Ira kieu
0 nguyen h04c Iii. dia chi cua mot bien nguyen. Tnrong vao phai la mot so
nguyen he 8.
Nhap vao mQI so nguyen dai he 8: doi so nrong irng phai la con 1m kitu
[0 long hoac HI dia chi cua mot bien long. Truong vao phai Ill. mot so
nguyen he 8.
Nhap vao mQI so nguyen he 16: doi so luang ung phai [a con lro kieu
x nguyen hoac Iii diu chi cua mot bien nguyen. Truong vao phai la mQI so
nguyen h¢ 16.
Nh~p vao motsd nguyen dai M 16: doi so luang tmg phai Iii con Ira
Ix kitu long hose [a dia chi ella mOl bien long. Truimg vao phal lil mot so
nguyen he 16.
c NMp vao mot ki II!: doi so tuong Ung phai \11 mql con Iro kl II! hoac dia
chi cua bien ki tu, Tnrong vao [a m¢t ki II! bffl kl.
Nh~p vao m¢1 xau kl II!: d6i so luang ung phai la con Iro kitu kf II! hoij.c
s [il dia chi cua m¢t mang ki W. Tnrong vao [a mot day kf II! b:ll kl khong
chua dau each, Tab va dffu xu6ng dong. Kf II! NULL '\0. se duoc tl!
d(lng them vao cu6i cua kel qua nhan dut;lc.
f hoac e Nhap vao mot s6 thuc kieu float: dOi sO IU"<mg tffig phm [a con lro kieu
float hoac [a dia chi cua mot bien float. TruOng vao phai \iI met so thirc.
Nhap vao mQI so tlurc kieu double: doi s6 luang tffig phai \11. con Iro
[f hoac [e kieu double hoac Ill. dia chi cira m~1 bien double. Tnreng vao phUi Ill.
mot so thuc. Vi dlJ.1-15. each dung dac ta trang ham scan! Xet dean chuang trlnh sau: int k ;

float x, Y ;

ch ar ch 1 [61, ch2[6] :

23

seanf("%f%5f%3d%3s%s", &x, &y, &k, eh1, eh2) (11); Thl voi dong vao nhu sau:

34.24e~ 1 36 12345678b (Enter)

ham se bien d6i cac ki tu cua roan be) twang vao thu nhat "34.24e~i" thanh dang s6" thuc diu phay tinh 3.424 va gan cho bien x; cac ki tl! cua toan bo tnrong vao th(i hai "36" thanh dang s6 tlurc dau phay tinh 36.0 va gan cho bien y; ba ki tv d<iu tien caa tnrong vao th u ba "i2 3 " thanh dang s6 nguyen } 2 3 va gan cho bien k; ba ki tv tiep theo cua tnrong vao thu ba "456" thanh dang xau ki nr "456" va gan cho bien chi; va cac ki W con lai cua tnrong vao thu ba "7Sb" thanh dang xau ki tv "78b" va gan cho bien ch2 tluu y ch l va eh2 de'u dii bao gom ki tu kit thuc chuJi \0).

Vi du 1-16. Chuong trinh minh hoa each dung d~c ta % * trong scanf( ).

#incl ude'tstdio. h" #include" conic, h"

int mainO {

int a; long b: float e, d;

char Xau[25], eh;

printf("\n Hay nhap cae gia tri tuong ung cho a, b, c, d, Xau, va ch: \n"); (12) scanW%3d%ld%f%f%s%*c%c", &a, &b, &c, &d, Xau, &eh);

printf("\n Gia tri eua cae bien sau khi nhap la.m"):

printf("a=% 1 Od\n", a);

printf("b=% 1 Old\n" , b);

printf("c=% 1 0.2f\n", c);

printf("d=% 1 0.2f\n", d);

printf("Xau=\ "% 1 Os\ "\neh= '% 1 Oc'\n", Xau, ch); getehO;

return 0;

}

~ *************~*** •• *****~*********.*********~********.****** •• ****.*****.****~******~~.** *j

Ket qua chay chuong trinh:

Hay nhap cae gia tri tuong ung cho a, b, c, d, Xau va ch: 12345678 254.45e-3 573 ABC 67890

Gia tri eua cae bien sau khi nhap la:

a= 123

b= 45678

c= 0.25

d= 573.00

II Hai bi!!n chI va ch2 Iii. cac rnang ki tl! cho nen fa khOng phai dung roan UI xac dinh dia chi '&' cho chung, Trong chirong 3, muc 3.3.2 se ban ki hon ve van de nay.

12 Trong Turbo C 2.0 ta c6 th~ hien thi true tiep cac kf tu • " va kf tl! ,., rna khong can sir dung '\' va '\" trong chuoi dieu khien.

24

Xau=" ABC"

ch=' 6'

Trong vi du tren, neu ta bo di d~c ta %*c trong ham scanj() thi ket qua se khOng hien diroo dong ch=' 6'. Nguyen nhan la do sau khi nhap xau ki nr xong, may se doc ki tt! tiep thea tm« khong phan biet ddu each hay ddu xuong dong do dung dt;ie td %e d sau) vao bien eli. Do do thuc chat bien ch se chua dau each' , (ntu ta nh~p tren m¢t dOllg) hoac chua dau xuong dong "vt' (ne"u ta nlu;lp tren nhieu dong) va s6 6 khong duoc in ra. De xu 11 tinh hu6ng nay, ta them mot dac ta %*e vao tnr6c d~c ta %c khi d6 dac ta %*c se van doc dau each h09C dau xuong dong nhu mot ki tu blnh tlurong nhtrng khong luu vao bien nao ca.

Ch"y:

- Cling gi6ng nhu ham printfi}, gitra chuoi dieu khien va danh sach cac d6i phai diroc phan tach vm nhau bang mot dau phay.

- KhOng nen sir dung tnrong d trong dac ta neu khong biet r6 de) dai tnrong vao, D6ng thai cAn hru Y s6 dOl so: s6 cac d{ie td va s6 truang vao phai bang nhau.

- Khi nhap cho nhieu d6i cung mot hie thi cac gia tri nrong tmg voi cac d6i tren dong vao co the diroc viet tren cung mot dong inhung cdc truang vao phdn tach nhau hOi mot ho{ic nhieu ddu each hodc Tab) hoac tren nhieu dong khac nhau.

- Khong the nhap mot chu6i g6m Ilhie'u tit cho bien chuoi bang lenh scanf .

Vi du, Xet doan ChUC1ng trmh sau:

char TenD; rKhai baa m¢t mang kf tl/"I scanf("%s", Ten);

Thi khi ta g6 vao dong sau day: Nguyen Thi Lan Anh (Enter)

Bien Ten se chi chua dugc chu6i Nguyen rna thoi. De co the nhap dung diroc ca ho va ten ta ca.n dung bam nhap gets diroc khai 00.0 trong stdio.h thay the cho ham scanf ixem them muc 33.2).

~ Chuang trlnh se thoat khoi ham scanfi] khi mot trong cac dieu kien sau day

xay ra:

+ IlOgc dd xet he! cac dge ta (clio du vdll COil dOl) + IIO¢ic aa xet lief cdc do'; (mdc du vdn COil d{ic ta)

+ IIO¢ic g{ip mot su khong tuang thich giiia cdc ddc td va do'i tuong ung (nh{ip sai kilu).

Khi tra ve chuong trinh, ham scanft ) se tra ve mot gia tri nguyen bang cac tnrong vao dtl duoc chuyen dang va hru vao bo nhc,

- Khi thoat khoi bam scanfki tl,l' "vt' (Enter) van con nam lai trong stdin va co th~ lam anh huang den cac cau lenh khac cling dang lam viec voi stdin (vi du lam troi ham gets rgetchar ... trong muc 4 dum day). De khiI ki tv "vi' trang stdin nguoi ta dung mot trong nhtrng each sau:

+) Them ddc td %*c vao cuoi chuoi die"u kilil" cUa m6i ham scan! +) Dung hamfflush(stdin) di lam sach stdin.

25

- DOng vao se diroc do dQC thea tung ki nr (ke' cd ddu each, Tab va ki'if XU611g dong) neu ta sir dung cac kieu chuyen dang d~c biet sau day: c, [ ... j va [A ... j. VOi. kieu chuyen dang [tdp hap cac ki ltf nao do] ham scanfi] se Ian hrot doc cac ki 11! tren dong vao cho den khi gap mot ki tl,l' kh6ng thuoc t1j.,P cac ki 11! da duQC chi dinh trong cap dau []. Dei nrong trng phai la mot Call fro kieu char tro toi mot vung nhd du Ian. Truong vao HI. mot day ki tl! bat ki.

V6i kieu chuyen dang [A tap cdc ki tu nao do] ham scanfi ) se Ian hrot dQC cac ki W tren dong vao cho den khi gap mot ki nr thuoc t1j.p cac ki tl! da duoc chi dinh trong cap dau []. Dei urong img phai ta mot con tro ki~u char. Tnrong vao 13. mot day ki nr bat kl.

Vi d1;l1-17. Chuang trlnh minh hoa each Slr dung cua hai kieu chuyen dang dac biet [ ... ] va [A ... J.

#include~stdio.h" #incl ude" conio. h"

~ *~~~~~*~*.~*******************************************~*******************************~*~ ~/

int malnt) {

int a, b;

eh ar Xau 1 [25], Xa u2[25];

printf("\n Hay nhap cae gia tri tuong ung eho a, Xau1, Xau2 va b:\ \n"): sea nf{" %d % "e%[O 123456789]% [AD 123456789]%3d",

&a, Xau1, Xau2, &b);

printf{"\n Gia tri eua cae bien sau khi nhap la:\n"); printf{"a=%d\n", a);

pri ntf("Xau 1 =\ "%s\"\nXau2=\"%s\"\n ~, Xau 1, Xau 2); printf{"b=%d\n", b);

geteh{):

return 0;

}

.~ .... *** •• ** •• * ** ... *** '* .. **. **** ***** ***** ***** *- *"**** ** ***1r1c:"/Ir"f/r *'*"'*''* ...... * '*'*." 1t1c:"/Ir * ** * * 1c:"k"" *"o:t '*'*"* * * ****. * /

Ket qua chay clurong trinh:

Hay n hap cae gia tri tuong u ng cho a, Xau 1, Xau2 va b: 35 12345 ABG67890

Gia tri eua cae bien sau khi nhap la: a=35

Xau1="12345"

Xau2=" ABC"

b=678

Biii tap:

a) Hay giai thich heat dong cua chuang trinh tren,

<, b) Tai sao phai sir dung dac ta %*c trong cau lenh scanf (j tren, neu khong

c6 dac ta nay thi ket qua in ra man hinh se nhu the' nao?

c) Neu trong dong vao, khoang each gifra so 35 va 12345 la hai dau each thi hien nrong gl xay ra?

26

d) Tai sao trong Xau2 cac lei W dAu lai chua hai Mu each? 3. Cdc IuUn khac dung di trinh bdy dit li~u ra man hinh a) Hdm puts tduac khai bdo trong stdio.hs

DUng de dua mot chuoi lei (1,1' fa man hlnh thong qua stdout. D'!-ngham:

int putsiconst char ·5); Ho¢d9ng:

Ham se dtra chuoi do can tro s qulin Ii va mot ki tu '\/1' len stdout. Nell thanh cong, ham tra ve kf tu cuoi cung dugc xuat tcliinli la ki tlf \" '), ngiroc lai ham tra ve EOF(l)).

Vi du cau lenh putst'Hello"): se dua fa man hinh dong chi! "Hello" sau do

xuong dong (11lO11g duang viti cdu I¢nl! printf("Hel/oln");).

b) Ham putchar (dl1l/c khai bao trong stdio.h)

Dung d~ dua mot kf nr fa man hlnh thong qua stdout. D,!-ng ham:

int putchar(int c);

H oat d9ng: .

Ham se dua mot lei tl,1 c dmri dang rna ASCll fa stdout, nell thanh cong ham tca ve ki tu duoc xuat, nguoc lai ham tra ve gia tri EOF.

Vi du CAll lenh putchar ('8'); se dua rna 66 fa stdout rna ket qua la mot ki tu

'8' drrcc hi~n thi fa man hinh tai vi tri hien thoi cua con tro man hinh.

c) Ham putch (kiwi bao trong conio.hy

DUng de dua mot ki 11,1' fa cira s6 van bin man hlnh (khong qua stdouti. DCJng ham:

int putch(int c); Ho¢dtjng:

Dua mot ki tu c6 rna ASCII la c len cim s6 van bin man hinh, Ki nr se diroc

hi~n thi thea mau x.fc dinh trong ham textcolor. . .

Vi d1,1 cac cau lenh sau textcoior(RED); putch(, A'); se cho hien mot chi! 'A' mall do len man hinh,

4. Cae ham khac dung di nh~p dit li~u vao til' ban phim a) Ham gels tduoc kiwi bao trong stdio.h)

Dung d6 nhap mot ChllOi ki tlJ til ban phim thong qua stdin. DCJng ham:

char " gets(char "5); HoCJ/ d9ng:

Ham tien hanh nhan mot day kf tu tir stdin cho den khi g~p ki ur '\/1' (do do nelt trong stdin dii co san ki tu '\n' rdi thi ham gets sf! khong clio nguai su dung

13 EOF la m¢t ten hang duoc dinh nghia trong stdio.h, Hay xem them chuong 5.

27

nhdp dfi lieu vaa niia, ta n6i ham gets da hi lroi). Ki tl! '\n' se bi IO,!-i khoi stdin nhung khong diroc d~t van chuoi, Chuoi nhan diroc se diroc nr dong b6 sung them ki nr '\0' de danh dau su ket thuc chuoi roi diroc dat vao vung nho do con tro s tro toi, Ham tra ve dia chi cua chuoi nhan diroc.

Vi du d~ nhap tir ban phfm ~Qt c·hu6i kf tl! rei hru vao bien Hol'en ta viet

nhu sau: char HoTen[25]; gets(HoTen);

b) Ham getchar (d/f{1C khai bdo trong stdio.lu Dung dt nhan mot ki tl! tir stdin.

Dang ham:

int getchar(void); HOf,lt dong:

Ham se tien hanh nhan rna ASCll cua mot kf nr tir stdin va tra ve ki nr vira

nhan dLl(_1C.

Vi du dt nhap mot ki tu tu ban phim vao bien c ta c6 th~ viet nhu sau: char c: c=qetchart):

c) Ham getch va getche (kiwi baa trong conio.lu

Dung de nhan mot kf nr tnrc tiep tir bt? dern ban phfm tkhong qua stdiny. Dang ham:

int getch(void); int getche(void);

Hoat dong:

Neu [rang bo dem ban phim c6 san lei nr, thl ham nhan mot kf (I! (rang do.

Neu bo dem r6ng thl may tarn dirng cho den khi ngiroi sir dung go vao mot phim bat ki tkhong b&l buoc phdi kel thtu: bang phim Enter nhu cdc ham lam viec vai stdin do d6 cdc ham nay thuang duac str dung dl bdt phim khi viet Menu ... ). Phfm vira go se diroc hien len man hinh neu dang dung ham getche, con voi ham getch thi ki nr khong diroc hien ra man hinh, Ham se tra ve kf nr vira go.

5. fJ(ie dilm ella cac ham tam vi¢c vOi stdin

- Neu tren stdin da: co san dfr lieu thl cac ham nay se nhan mot phan dfr lieu d6 tuy thea yeu cau cua tung ham. Phan dfr lieu eon lai (neu (6) van b tren stdin.

- Phfm Enter dung de ket thuc qua trinh nhap SI! van rum lai tren stdin.

- Neu stdin khong eo hoac khong du dfr lieu thea yeu cau ella cac ham thl

may se tam dirng d~ ebb' ngiroi sir dung dua them dfr lieu tu ban phim len stdin cho den khi phim Enter duoc nhan,

Vi d~ 1-18. Xet doan chuang trlnh sau:

char ch1, ch2; int a, b;

printW\nHay nhap gia tri cho cae bien ch1, a, b va ch2");

ch l=qetchart): 1* ham lam vi~c voi stdin *'

scanW%d%d", &a, &b); 1* ham lam vi~c voi staln " ch2=getcheO: 1* ham [am viec tnrc tiep voi b(l6~m ban phim "t

28

printf("\nCac gia tri ch1= %c, a= %d, b= %d va ch2= %c~);

Neu doan chuong trinh tren duqe thtrc hien thl voi dong vao:

A123 4568 (Enter) V

se eho ket qua ohu sau: Cae gia tri eh1= A. a= 123, b= 456 va eh2= V

Co diroc ket qua nay la do khi gap ham getchar tit ca cac ki nr nhap nr ban phim se duoc chuyen toi stdin cho den khi gap ki tu '\n'. Ki tu dAu tien cua dong vao se diroc chuyen cho ham getchar va gan cho bien chi (ki tif A). Cac ki nr con lai vAn con nam tren stdin (bao g6m 123 456B va ki It! in '), Do do kill g~p cau lenh tiep thea scanfr%d%d~, &a, &b); may khong can cho ngiroi sir dung nhap dir lieu vao tir ban phim nira rna chuyen tnrong vao thir nhat "123" c6 san trong stdin thanh s6 nguyen thea d~c ta va dua VaG bien a; tnrong VaG thu hai "456B" thanh so nguyen 456 (ki tu 'B' van con tren stdins va dua VaG bien b. Khi gap ham getche do bo dern ban phim van chua c6 ki tl! nao (m<Zc du stdin win con ki tu 'B ') cho nen may se chn ngiroi sir dung barn mot phim bat ki, phim nay se duoc chuyen cho ham getche va dua VaG bien ch2 (ki tu V).

1.3. cAU TRUe MQT CHUONG TRINH C DON GIAN

Cau trtic dan gian cua mot chirong trinh C tlnrong duoc viet thea trinh nr sau: + Cac chi thi tien xir li

#include #define + Ham main

Trang d6, cac chi thi tien xu li dung de hieu chinh lai chuang trlnh nguon tnroc khi bien dich n6 thanh mot chuang trlnh chay diroc. Trong ngon ngir lap trinh C, c6 nhieu chi thi tien xu li dtroc sir dung voi nhieu muc dich khac nhau, y nghia va each sir dung cua tirng chi thi CI,I the duoc trmh bay them trong phu luc II. Trang chuang nay, ta chi quan tam chu yeu tai chi thi #inelude va chi thi #define. chi thi #define chiing ta da lam quen trong muc 1.2.7. Chi thi nay dung de dinh nghia ra cac Ten luing va cac Macro c6 pham vi loan c~c til hie dinh nghia cho den cu6i tep g6c hoac cho den khi duoc dinh nghia lai sau chi thi #ufldeJ C6 nghia la mot Ten hdng hay mot Macro tir khi duoc dinh nghia ra hOi chi thi ttdefine thi gia tri cua n6 luon duqc thay the' a bit kl dau trong chuang trinh rna n6 xuat hien ikhong phu thuoc vao vi¢c no flam trong khOi [fnll hay if ben ngoai cdc khO'i l?nh).

Chi thi bao ham tep #include <[Dubng_dAn\]ten_t¢p> dung de chen noi dung cua mot tep khac VaG chuang trlnh ngu6n tai dung vi trf rna chi thi d6 xuat hien. Tnroc kill dich, chuong trinh bien dich Turbo C se tlrn tep theo ten va dubng dan ghi trong <Duang_dfut>, neu tim thay thi toan b¢ t¢p d6 sf: diroc chen VaG chuong trinh nguon tai nci chi thi #include xuat hien, ngiroc lai mot thong bao loi se diroc dua ra:

Unable to open in elude file '/ DIIi'tng_ ddn] tell tep .

C6 hai each vier khac nhau cho chi thi #include. D61a:

#include <[DLfO'ng_d~Ill\]ten_ti;lp>

#include "[£)ucrng_dan\]ten_t~p"

29

each thuc lam viec cua hai dang nay chi khac nhau khi khong c6 thong tin v~ duong dan. Theo dang 1. trinh bien dich se chi tim tep can chen trong thu muc INCLUDE cua Turbo C. Con theo dang 2, tnroc tien trlnh bien dich se tim tep dn chen trong thu muc chu, neu khong thay thl tiep tuc tim trong thumuc INa..UDE cua Turbo C.

cs« j:

- Chi thi #include phai dtroc viet tren mot dong.

- Chi thi #include co the baa bam nhau.trong cac tep.

Vi du, neu trang tep g6c Cl'Chinh.c co chua chi thi #include "alc ". Trang tep al.c nay den hrot no lai chua chi thi #include "alc". Khi bien dich tep Cl'Chinh.c thl dieu gl se xay ra? Tnroc tien, trmh bien dich se tim tep a2.e trang thu muc chu va trang thu muc INCLUDE, neu tim thay noi dung rep nay se diroc chen vao dung vi tri cua chi thi #include "a2.c" trong tep al.c (lieu t¢p tlay t611 tai hoac trong thu muc INCLUDE IIOiJ.c trong thu muc chu). Ta nhan duoc tep alc moi, tep rnoi nay lai diroc chen thay the cho chi thi #illclude "al.c" trong tep gee, Nhu vay tnroc khi bien dich ca hai tep al .c va a2.c deu diroc ghep vao tep clurong trinh goc nho hai chi thi itinclude.

- Su dung chi thi ttinclude ta co the t6 chirc mot chuong trinh Ian tren nhieu tep khac nhau do nhieu nhom lam viec khac nhau rna ve mat logie van diroc coi la viet rren mot tep,

- Dung chi thi #illclllde tao kha nang eho ngiroi lap trlnh tir xay dung ra cac thir vien cua rieng rninh. Tuy nhien, viec t6 chirc cac tep thu vien va cac mo dun chuang trinh phai tuan thu mot s6 quy tic nhat dinh, dieu nay se diroc trinh bay ki han trang pIJI} II}C fl.

- Chi thi #include cling thirong duoc su dung trang ngon ngu lap trlnh C de ghep cac tep tieu de c6 dang *.11 vao chuong trinh, Cac tep lieu de cua Turbo C tnhu stdio.h, conio.h, dos.h .. .) dung M chua khai baa cua cac ham chuan, dinh nghia cac hang va cac kieu du lieu chuan trang ngon ngu, Trang mot chuang trlnh U'ng dung, neu ta muon sir dung lai cac ham, cac hang hay cac kieu du lieu chuan da diroc dinh nghia nay, ta pbai dung chi thi ttinclude de k€t n6i mot tep lieu de wang ling co chua khai baa do. Vi du, de S11 dung cac ham vao I ra trong Turbo C ta can them vao chuang trlnh g6c cau lenh sau: ttinclude "stdio.h ''.

Ham main l;,ti co the la ml)t trong nhung dang sau day:

Dang 1: mainO

{

1* cac khai bao narn a day·/ 1* cac I~nh nam a day·'

}

Dang 2:

KiE§u_tra_ve main(void)

{

,. Cac khai bao nam a day·/

30

l" Cac I~nh nam a day"l return Gia_trUra_ ve;

}

Dang 3:

[Kielu_tra_ve] main(int i, char "str[]) {

r cac khai bao narn a day" I rCae I~nh narn a day"l return Gia_tri_tra_ve;

}

M6i bam main nhln chung baa gam 2 phan, phan dau bam va phan than ham. Phan dliu ham baa gam len ham va co the co d6i s6 cling nhu gia tri tra ve. Phan than ham bat dau bang mot ki ur '{' va ket thuc bang mot ki tu '}': Ben trong than ham la toan bo cac lenh duqc sir dung trong chuang trinh. Dang 1 va Dang 2 Iii hai cAu true thuong diroc su dung nhat, chung chi phan biet nhau ?:J gia tri tra ve cua ham. Gia tri tra vI! Iii gia tri thea mot kieu nao do rna he dieu hanh nhan diroc sau khi chirong trlnh ket thiic. H~ dieu hanh se can cu vao gia tri tra vc cua m6i chuang trinh denMn biet tmh trang hoat dong cua cac chuang trinh do.

Df,lng 3 la cau true d6i dong lenh, no cho phep mot chuang trlnh khi chay co the co tham s6 dAu vao (vi du setup I? ... ). Trong do, i se chua s6 tham so, con cac phan tu cua mang hlnh thuc str[] se chua dia chi cua cac tham s6 dua vao dum dang cac chu6i ki tu, m6i tham s6 Sl! phan biet nhau b?:Ji It nhat mot dau each. Tham s6 dau tien SI! la ten chuang trinh cung voi dtrong dan va diroc hru trong strlil], cac tham s6 con 1~ se Ill. nhtmg tham s6 cua chuang trinh. Trang than ham main cluing ta co the sir dung i va str nhu cac tham s6 dAu vao diroc nhap tir ban phim cua ham M xu li thea yeu cau ~t ra.

Vi d~ 1-19. Chuang trlnh minh hoa sir dung df/i dong [fllll.

#include~stdio. h" #include"conio. h"

I" Gia sa chU'ang trinh dllc;fC bien djch thanh VD _18.exe trang thu rnuc C:\TC\ *1 1* Trong chl1Cfng trinh ta c6 the; thay dO'i each Xli If cua cac tham s6 tuy y "I

void main(int i, char *str[]) {

int k;

printf("\nTen cua chuong trinh dang chay la: %s",str[O]); for(k=1 :k<i;++k)

printf("\nTham so thu %d la: %SH, k, str[k]); getchO;

return;

}

Ket qua chay chuang trinh nhu san:

C:\ TC\B I NWD _18. exe I? lis fie lu 1m In

31

Ten cua chuang trinh dang chay la: C:\TC\BINWD_1B.exe Tham so thu 1 la: I?

Tham so thu 2 la: lis

Tham so thu 31a: lie

Tham so thu 41a: lu

Tham so thu 51a: 1m

Tham so thu 6 la: In

~ ************************.**************.*********~****************~**************~~~***** ~/

1.4. MOl TRUdNG L~P TRINH TURBO C 1.4.1. Moi trueng ket hep

C6 hai each khac nhau d~ viet chuang trmh trang Turbo C. Mot la he thong dong lenh C, thea do viec soan tluio, bien dich. , lien klt va thuc hifn duqc goitir dong lenh DOS nlnr nhiing cong viec rieng biet do cac chuang tr1nh rieng biet dam trach, Thea each nay thong thirong cac thaa tac bien dich va lien ket se duoc thuc hien trang mot tep tin * .bat de giarn do thai gian cho ngiroi l~p trinh. H¢ thong dong lenh C thtrong duqc sir dung d~ lien k€t cac mo dun diroc viet bang ngon ngir l~p trlnh Assembly hoac dung d~ dich cac chuang trinh 160. Trang giao trlnh nay khong de cap d€n each lam viec nay.

H¢ thong thrr hai de tao chuang trinh 13. dung moi truong ke't hop cua Turbo C (Integrated Development Environment -IDE). Trong moi tnrOng nay da tfch hop tat ca cac thao tac can thiet de phat trien chuang trlnh nhu soan thdo t¢p ngu6n, bien djch tep ngu6n thanh cac file d6i nrong * .obj, lien kc!t cac file d6i tuong thanh chuang trlnh chay duoc, sUa l&i va chay chuang trinh,

1. Cii.i dtJ! h~ thi/ng

Cai d~t he thong lap trinh Turbo C bang each chay chuang trinh install.exe trang rna cai d~t thu nhat, Tien trinh cai d~t se hoi ten 6 dia chua cac tep ngu6n. (m¢ic dinl: ld 0' A) va dirong dan tai thu muc se chna cac t¢p duqc cai d~t cua Turbo C (m¢c din" Iii C:\TC). Tien tnnh cai d~t se sao chep cac tep tieu d~ *.h vao thir muc can C:\TC\INCLUDE\ cac tep tin thu vien * Iib va tep dich * .obj vao thu rnuc can C:\TC\l.IB\ va cac rep tin khac cua moi tnrong le€t hop Turbo C vao thir rnuc C:\TC bao gam:

-TCC

-1LINK

-MAKE

-OREP

-TOUCH

-CPP

- TCINSf

-TUB

-UNPACK

- OBJXREF

- BGIORJ

32

Dung M bien dich thea dong lenh

Dung d~ lien ket khi bien dich thea dong lenh, Dung de quan li tep tin.

Dung de tim chuoi trang nh6m tep tin.

Dung de cap nhat ngay thang va gio cua t¢p tin. Dung cho cac tbao tac tien xir li,

Dung de d~t cau hmh cho moi tnrong TC. Dung quan 11 cac chuang trinh tbu vien. Dung di! bung t¢p tin.

Dung M tham khao cheo cac tep tin d6i nrong.

Dung M d6i trinh dieu khien d6 hoa sang tep tin obj,

- THELP Dung d~ tro giiip trong qua trlnh sir dung TC.

- README Dung d~ doc cac tep tin tro giup readme.

Trong do, tep tin quan trong nhat la TC.EXE, n6 chua toan bo rnoi tnrong ket hop cua Turbo C. ~ c6 tM chay dtroc TC .EXE tir bat kl thu muc nao du6'i dong lenh DOS ta can them dong lenh sau vao trong tep AUfOEXEC.BAT:

SET PATH=C;\TC (1I1u TC ndm trong thu muc khac thi phdi chi r5 ten thu muc do sau PKfH=).

2. Sa d~ng moi truong kg h9P eua Turbo C

~ khOi dQng mOi tnrong ket hop cua Turbo C, tir dau nhac cua DOS ta go dong lenh sau dAy: TC.EXE sau d6 go ENTER. Ket qua ta thu duoc firm hinh giao dien ella Turbo C cO dang nhu sau:

t 1 L " '

._-- - ---'

a_It 1.1. Man hlAlt giao ~ khi thCri dQng Turbo C.

TJ'.II(jc kbi hit diu llm ~ voi moi t.nWng ke"t bop cua Turbo C. ta can xac 14P 4i eM JUab cia mot t:JU()ng trong tep tin TCCONFIG.TC (neu ta chua rhay d6i gi.til khi eli ~ thi e6 til! bO qua buoc nay). ~ thuc hien duqc viec nay ta chon Opticn->DirectCJries sau d6 go duOng dAn ella thu muc con \JNa...UDE van hop tho~ Iaciude Directories (mac dinh II C:\TOlNQUDE), go duoogdan cua thu In¥C con \ UB van hI)p thoai Liblary Directories (mac dinh la C:\TO.Lill). Bam phim ESC r6i chon Save options de: hru lai cac thay dOi vao tep cau hinh ella moi tnrong.

Khi da 0 trong moi trubng cua Turbo C ta c6 the thvc hien cac thao me sau: - Bam Fl d6 xem huong dAn v~ tinh hinh hien tai,

- ~ FlO de v~ Menu chfnh,

- Bam d6ng thai phim Alt va chit cai d~u tien cua moi Menu de chon ttmg

Menu con. Vi du ta bam Alt~F d~ vao Menu File. Alt-E dJ vao Menu Edit...

Cac Menu ehinh trong moi tnrong Turbo C c6 th~ dtroc mo ta nhir sau:

Menu File c6 cac chirc nang sau:

33

03-G'fffHL TC

· Load (F3): N<;Lp mot tep da: co vao d~ lam viec,

· Pick (Alt-F3): Lay mot tep trong danh sach 8 tep da: rna tnroc d6.

· New: D~ t<;LO tep moi voi ten mac dinh la Noname.c

· Save (F2): Ghi tep dang SO<;Ln thao ra dia.

· Write (0: Ghi tep dang soan thao ra ilia voi ten moi,

· Directory: Hien noi dung thu muc hoac t;l.p h9'P cac tep can quan tam.

· Change dir: Hien noi dung thu muc hien ~ va cho phep d6i 6 013 hoac thu muc.

· OS Shell: T<;Lm thoi roi bo rnoi tnrongker h9'P d~ tra ve cau lenh ciia DOS.

Muon tra lai moi tnrong ket h9'P ta go vao Exit.

· Quit (Alt-X): Thoat khoi moi tnrong ket;p9'P cua Turbo C d~ tro ve DOS.

Menu Edit dung d~ khoi dong chuang trinh soan thao van ban co san cua Turbo C. Man hinh soan thao thirong luon xuat hien mac dinh khi ta khoi dong moi tnrong Turbo C.

Menu Run c6 cac clurc nang sau:

· Run (CtrI-F9): Khoi dong qua trinh tu dong bien dich, lien ket va chay chuang trlnh thong qua cac thong tin dll chuan bi san trong chirc nang Project name cua Menu Project. Neu khong dung Project name thl chuang trinh co ten trong hop sang Primary C file (Menu Compile) diroc xet. Neu hop sang nay rong thi chuang trinh dang SO{Ul thao hien tai trong cira s6 Editor duoc xet (xem them phu IIfC I d€ bier ro han vi Project name).

· Program reset (Ctrl-F2): Lap lai che d¢ thirc hien toan b¢ chuang trinh.

· Go to cursor (F4): Thuc hien chuang trmh cho den dong lenh chua con tro,

· Trace into (F7): Thirc hien tirng lenh mot d~ go roi.

· Step over (F8): Thirc hien tirng cau lenh va xem loi goi ham la mot Call lenh tkhong chay tung /¢nh cua ham. do nhu F7).

· User screen (Alt~F5): Tro lai man hinh su dung d~ xem ket qua do chuang trinh tao ra. Bam Enter se tnJ v6 moi tnrong ket hop cua Turbo C.

Menu Compile c6 cac chtrc nang sau:

· Compile to OBJ: Dich mot tep *.C (thea tlnr nr UU tien nhtr d6i voi lenh Run trong Menu Run) thanh tep *.Obj.

· Make EXE file: Dich va lien ket M tao thanh t¢p * .exe. Thtr tll chon cac tep ngu6n cting nrong nr nhu tren,

· Link EXE: Lien ke't cac tep * .Obj va * .Lib de tao thanh tep chuang trinh thuc hien * .exe.

· Build all: Dich lai va lien ket d~ tao thanh tep chuang trlnh chay duqc * .exe.

Tlnr tu cac tep ngu6n cung diroc xac dinh nhu tren,

· Primary C file: Dung d~ chi dinh cac tep *.C can diroc bien djch va lien ket thanh * .exe.

Menu Project c6 cac clurc nang sau:

· Project name: Dinh nghia mot tep project chua thong tin ve cac tep can dich va lien ket (xem them phu luc I).

34

· Break make on: Xac dinh lieu viec dich c6 bi dirng khi gap Warning hoac

Error hay kh6ng.

· Auto dependencies: Rat it dircc sil dung.

· Clear Project: Dung d~ xoa tep Project va dii.t lai cira s6 Message.

· Remove message: Xoa bO cua s6 Message.

Menu Option c6 cac chirc nang sau:

· Compile: Dung M chon mo hlnh b¢ ~a (chon Model) va xac dinh dQ dai

eire dai cua ten trong chuang trlnh (chon Source).

· Linker: Chon each thirc lien ket,

· Environme~t: Thier lap moi tnrong.

· Directories: Thiet lap cac thu muc lien quan Mn qua trlnh bien dich,

· Argument: Dua vao cac tham s6 dong lenh cho chuang trlnh chay trong moi tnrong Turbo C (nlu chuang trinh duoc viet duai dang dOl dong l¢nh).

· Save option: Ghi lai cac thay d6i trong trong Menu Option.

· Retrieve option: Khoi phuc lai thong tin option tir mot tep nao d6.

1.4.2. Cac tep tin thuong duoc sir dung trong ngon ngu I~p trlnh C - Cac tep tin tieu d~ "'.h chua trong thu muc \TOJNCLUDE\

- Cac tep tin tlnr vien *.lib chua cac doan chuang trlnh dii diroc bien dich rna

nguyen rnau ella chung diroc khai bao trong cac tep tieu de wang img, Khi can su dung ham nao thl chi doan chuang trlnh cua ham d6 diroc sil dung (chIC khong phdi toan b¢ t¢p tin thu vien ducc Chell vao). Trong ngon ngii lap trinh C c6 5 tep tin thu vien chuan d6 la cs.lib, cc.lib, em.lib, cl.lib va ch.lib nrong irng voi 5 mo hlnh bo nhrr (14) cua Turbo Cia small, compact, medium, large va huge. Thong thirong ta chi sil dung mo hlnh small, do d6 chi can file cs.lib la du.

- Cac tep tin thu vien dich (* .obj): D6 la cac tep tin rna toan bQ noi dung cua n6 se duoc ket n6i van chuang tr1nh dang duoc bien dich neu chuang trlnh d6 dn den cac rna lenh M thirc hien nhieu chirc nang sau khi chay nhu dien dich d6i dong lenh ... Trong ngon ngii lap trlnh C co 6 tep tin thu vien loai nay wang img voi 6 mo hlnh b¢ nho d6 la COT.ob}, COS.ob}, COC.ob}, COM.ob}, COL.ob} va COH.ob) (COT.ob) tuong ting vm mo hinh Tiny).-

- Cac tep tin thu vien toan hoc: Dung cho cac phep roan dau phAy dong, C6 5 tep tin nrong rmg voi 5 mo hlnh b¢ nho (me hlnh Tiny dung chung voi small) d6 la maths.lib, mathc.lib, matlun.lib, mathllib va mathh Iib. Ngoai ra, kill lam viec voi cac s6 dau phay dong ta cling can dung themfp87.lib hay emu.lib. Tep tin dau tien dung cho may c6 bo tien xu li Coprocessor 8087, con tep tin thu hai dung d~ mo phong hoar dong cua 8087 bang phlin memo

1.4.3. each viet va chay chuang trinh trong mol truong ket hop

De tao mot tep tin chuang trinh ngudn moi c6 ten VD.C ta c6 th~ lam nhu sau, tai dau nhac cua DOS ta go:

Tc.exe VD.C

hodc khdi d¢ng moi truong kef IWp bang cdu lenh Tc.exe roi sau d6 dung Menu file->Write to de' ghi thanh tep VD.C vao ilia.

14 D6 Ia each 16 chirc cac dO<1Jl chuang trlnh trong b¢ nho.

35

Thea ca hai each ta deu nhan diroc man hlnh Edit nhu sau:

Hlnh 1.2. Man hmh lam viec cua Turbo C khi dang thao lac v6i tep VD.C

Trang cira sci Edit cua moi tnrong ket h<;1P ta co the thuc hien cac thao tac sau

day trong khi soan thao chirong trinh:

· Bam F2 d~ 100 chuang trlnh vira soan thao,

· Dung cac phim mi1i ten d~ di chuyen can tro.

· Bam Ctrl + -> de chuyen can tro sang phai mot til.

· Bam Ctrl + -c- d~ chuyen can tro sang trai mgt nr,

· Bam Home, End M chuyen coo tro ve dau hoac cu6i dong.

· Bam Ctrl+Home d~ chuyen can tro ve dau trang man hlnh.

· Bam Ctrl+End d~ chuyen can tro ve cu6i trang man hlnh.

· Barn Page Up de chuyen can tro leo trang man hlnh tnrcc,

· Barn Page Down de chuyen can tro xu6ng trang man hinh sau.

· Bam Ctrl+Page Up de chuyen can tro ve dau chuong trlnh.

· Bam Ctrl+Page Down de chuyen can tro ve cu6i chuang trlnh.

· Bam BackSpace M xoa ki nr ngay truck con tro,

· Bam Delete M xoa ki tv ngay sau can tro,

· Bam Ctr! + T de xoa tit dang chua can tro.

· Bam Ctrl +Q+ Y M xoa til vi trf can rro den cu6i dong.

· Bam Ctrl + Y M xoa dong dang chua can tro.

· Bam Ctrl +N M chen them dong tr6ng vao tnroc dong chua can tro,

· Barn Insert M chuyen d6i che dQ chen va de.

· Bam Ctrl+K+B d~ danh dau dau khoi.

· Bam Ctrl+Ks-K d~ danh dau cu6i khoi.

36

· Bam Or1+K+C M copy kh6i da diroc danh dau.

· Bam Orl+K+V de dan khoi da diroc copy.

· Bam Or1+K+ Y M xoa khoi da duqc danh dau,

· Bam Orl+K+P de in khoi ra may in.

· BAm Orl+K+W de ghi khoi da diroc danh dau ra dia.

· BAm Or1+K+R de chen noi dung file tren dia vao vi tri con tro,

· Bam Ctrl+Ks-H de bo viec danh dau kh6i.

· Bam Ctrl+Q+F de tim kiern van ban trong nci dung file dang soan thao,

· Bam OrI+Q+A de tim kiern va thay the van bin trong noi dung file dang soan thao.

· Ham Orl+0+1 de chuyen d6i che do can Iii trai,

· Bam Ctrl+Os-U M chuyen d6i che d¢ can Ie trai khi sir dung phim xoa BackSpace.

Chucmg trlnh sau khi viet xong c6 the bien dich, lien ket va chay nr dong bing

each bam cung hie Ctrl-v F'). Neu chuong trinh viet dung n6 se diroc bien dich, lien ket va chay ngay trong moi tnrong ket hop cua Turbo C. De c6 the dirng man hinh M xem ket qua nhan diroc thi 6 cuoi ham main, tnroc cau lenh refilm ta cho them cau lenh getchi ). Hoac ta c6 th~ dung chirc nang User screen bang each bam Alt-F5 M xem ket qua khi chircng trinh thirc hien xong.

1.4.4. Sua loi co phap va gO" roi clurong trlnh

Cac chirc nang sua 16i cu phap va go rei chuang trinh la mot phan trong rnoi truong ket hop cua Turbo C. Khi bien dich mot chuang trinh, neu gap 16i, trinh bien dich se thong bao cac 16i mac phai trong cira sci Message 6 cuoi man hinh (muon clio clla s6 fIliy hien toan bq man hinl: fa bdm F5). Khi chuyen con tro toi mot 16i nao d6 trong danh sach 16i nhan diroc thl dong lenh tai noi phat sinh ra 16i d6 cling duoc danh dau, ta c6 the bam Enter hoac Alt-E di! chuyen con tro toi cho e6 16i va sUa theo thong bao goi Y cua trlnh bien dich, Cac 16i nay deu la lbi ve mat cu phap. C6 nhilng wang hop, khi bien djch kh6ng e6 Ibi nhung chuang trinh bi lap vo han hoac cho ket qua sai. Cac lbi loai nay goi la cac 16i ve mat logic. De c6 the sua chua cac lbi logic trong Turbo C ta can sir dung chirc nang ga r6i chirong trinh cua moi tnrong klft hop d6 la chirc nang chay chuang trinh tirng biroc (F7 hodc F8) va chirc nang kiem tra cac gia tri ella bien (cu-a so' Watch). Muon lam xwit hien cira sci Watch ben dum man hlnh ta vao Menu con Windows roi sau d6 vao Watch. EX! chuyen deli giG'a cac cira s6 ta dung F6. Trong qua trinh ga roi, de quan sat su bien deli gia tri cua mot bien nao d6 ta phai dua ten cua bien d6 vao trong cira s6 Watch bang each chon "Add Watch" trong Menu Breaklwatcli hoac bam Ctrl-F7 sau d6 nhap ten bien va bam Enter. M6i IA"n nhap nhu vay chi c6 the cho mot bien rna thoi, mu6n nhap eho nhieu bien ta phai lap lai qua trlnh tren.

EX! c6 th~ tim diroc nguyen nhan ella cac 16i logic, thong tlurong ta cho chuang trlnh chay tirng buoc bing F7 hoac F8 sau d6 quan sat SI! {hay d6i gia tri cua cac bien nrong img trong cira sci Watch, tir d6 c6 thi! tim duoc nguyen nhan sai hong.

Trong qua trlnh ga r6i ta cling e6 kha nang thay deli gia tri cua mot bien nao d6 de quan sat nhttng thay dOi tren cac bien khac bing each dung ci'ra s6

37

I ~ (-

I

EV ALUATlON trong Menu Debug hoac bam Ctrl-Fd khi d6 tren man hinh se hien ra ci'ra s6 nhu hlnh 1.3.

...--------- ......... ---Result

...-------~------ Eualuate

...--~--------- New ualue_

Hinh 1.3. etra s6 Evaluation dung de thiet lap lai gia tri cho cac bien,

Nhap ten bien dn thay d6i gia tri trong h9P Evaluate, khi d6 gia tri hien thci cua bien se hien trong h9P Result. NMp gia tri rnoi cua bien VaG hop New value sau d6 tra ve; cira s6 Watch dt quan sat sir thay d6i gia tri cua cac bien khac bang bam ESC, hoac co th~ xem true tiep trong cira s6 Evaluation bang each go ten cac bien moi vao h9P Evaluate roi quan sat gia tri trang hop Result.

D~ ket thtic qua trinh go roi, bam Ctrl-F2 hoac vao Menu Run chon Program reset. Khi d6 bo nho dung eho viec go roi se diroc giai toa.

Chili

Chuang trinh bien dich co th~ sinh ra nhirng thong bao 16i khong chinh xac tir mot 16i tnroc do. Do d6 sau khi sua xong mot s6 l6i nao d6 ta nen bien dich lai ibdm F9) d~ bo di nhirng dong thong baa thira trang cira s6 Message.

1.5. MOT s6 vi D1,I MINH HO~ V Ao RA

Vi du 1·20. Lap trinh d~ may n6i chuyen voi nguoi sir dung. May "noi" bang cac cau lenh tren man hinh, con nguoi sir dung "noi" bang each go vao tir ban phim. N9i dung cU9C n6i chuyen tuy thieh.

~ ****.*~*~****** •• *~*************.***~******.****.**~~*************~*~*********.****.***** */

#include "stdio.h" #include "couto.h"

;- ********.**~~~~~****.**************.***~*~~.~****.***********~***.*****~*w************.** */

int mainO {

char traloi[20], ten[25];

printf("\nHom nay trol dep qua. Ban tu dau den vay ?\n"); oetsttraloi);

printf("Toi cung co anh ban a %s", traloi); printW\nBan ten la gi ?\n");

gets(ten);

printf("Chao ban %s", ten); printf("\nBan khoe chu ?\n"); gets(traloi);

printf("Toi dang ban di hoc, hen ban %s Ian sau nhe.", ten); printf("\nTam biet!"):

getehO;

return 0;

38

}

Ke'l qua chl,lY chuang trinh:

Hom nay troi dep qua. Ban tu dau den vay? HaiPhong

Toi cung co anh ban 0 Hai Phong Ten ban la gi?

Nguyen Van A

Chao ban Nguyen Van A Ban khoe chu ?

Toi dang ban di hoc, hen ban Nguyen Van A Ian sau nhe, Tam biet!

Vi dt,t 1-21. I*Chuang trinh minh hO<;1- nell kh6ng dung dung lei nr chuyen dang trong printfi ) thl ket qua in ra se sai * /

1* ***.************* ••• ********~*~**.********~~** •• ****~~*.******~** •• **********~~********** */

#include "stdio.h" #include "conlo.h"

/* ************~******.********~*~**.*******~***~*******************.**~*********.****.***.* */

int mainO {

int x=10;

long y=3478925;

printf("\nx=%1 Old\ny=% 1 Od", x, y); getchO;

return 0;

}

/* ~**********.**~*************************************.***~****************************.*** ~I

Ket qua chl,lY chuang trinh: x=361562122

y= 53

1* **~~*************************************.**.*~*******~****~***********~.*********~*~**.* */

Vi dt,t1~22, I*Chuang trinh dung sai d{ic td trong call lenh scanft], mac diu khong bi bao 18i nhung khi chay cho k~t qua sai*/

#include "stdio.h" #include "conlo.h"

int mainO (

int a; long b; float x; double y;

printf("\nNhap a, b, x, y\n"); scanf(,'%ld%d%lf%f', &a, &b, &x, &y);

39

printf("\na=%10d\nb=%10Id\nx=%10.2f\ny=%10.2r, a, b, x, Y); getchO;

return 0;

}

Kit qua chf1-Y chuang trinh:

Nhap a, b, x, Y

2346 447895 347 246 a= 2346

b= 119592343 x= 0.00

v= 5.54968399101 894023000000000ooooooooooooOe+ 191

1* ************ •• ***~************** •• *~**************.** ••• **************.********.~******** */

1.6, CAU HOI V A sAl T ~P

1. Diem khac biet giifa ten trong ngon ngir l~p trinh eva trong Pascal la gi?

cho vi du,

2. Di!-t 10 ten hop l¢ trong ngon ngtr l~p trinh C.

3. Hay viet 15 ten khac nhau tu cac chir cai A va a.

4. Ngon ngfr lap trinh C co nhimg d~(' tnrng gl?

5. Trang ngon ngfr lap trinh C c6 nhirng kieu dit lieu chuan nao? each sir dung cua ttmg loai d6?

6. Khoi lenh dung de lam gi, vai tro cua n6 trong chuang trlnh ?

7. Trinh bay ve pham vi siI dung va thoi gian t6n tai cua mot bien, Vai tro cua chung trong chuang trinh.

S, CO nhirng Ioai hang nao? each djnh nghia va siI dung cua ten hang va

bien hang.

9. Dac tnrng ella mot cau lenh trong ngon ngil lap trlnh C Ia gl ?

10. Hay thirc hien cac vi du mau bang may unh,

11. TIm ch6 sai trong doan chuong trinh sau day:

#include "stdlo.h"

rnainO

{

printfnna=%10.0f, b=%10d, c=%101d, d=%10d", ·3456, 25e3, 4635,456398461 );

}

Sira lai cho dung r6i thuc hien tren may tinh, 12. Viet chuang trlnh in mot dong voi noi dung sau:

N=365

Bang each sir dung cac loai hang khac nhau: hang diu phdy dong, hang nguyen, hang long, hang nguyen he 8, hang nguyen M 16, hang ki tl,l' va hang xau ki tu,

40

13. Tun cac chO sai trong doaa chuang trlBh sau: {

Float a, b=2; {

int a=10;

float c=a'b, d=a+b;

}

printf("\na=%10.2d, b=%10.2f, c=%f, d=%10.2r, a, b, C, d);

} .

Sua chua va b6 sung de duoc mot chuong trinh hosn t~n, sao d6 th1JC

hien tren may tinh. .

14. Cho 3 s6 A=555; 8=;-4.3; C=2100000000. Hay vilt chuang trlnh duicac dli lieu nay vao may Mng hang sau d6 dira ra man hinh theo quy each dung 14 vi tri trong d6 c6 3 s6 le neu la 56 thee,

15. Viet chuang trinh nhap ho ten, ngay thang nam sinh cua m¢t hQC sinh vao may roi dua ra man hinh, mOi dilli¢u tren mot dong.

16. Viet chuang trlnh nhap mot ki tu chtr thuong tir ban phim, sau do dua fa man hinh iJ dang chil hoa.

17. Viet lai chuang trlnh vi du 1-20 voi n¢i dung phong phti han.

18. TIWe hanh sii dung cac tien Ich ga r6i ella Turbo C de tim ra chO sai cua

chuang trinh dung dl! hoan vi noi dung cua hai bien sau day: #include "stdlo.h"

#include "conio.h"

void HoanVi{int, int);

int main(void)

{

inta, b:

pfintf("\nHay nhap hal so nguyen a va b \n~); scanf("o/odo/od",&a, &b);

printf("\nGia trl cua a truoc khi hoan vi la:\na= %10d", a); printf("\nGia· tri eua b truoe khi hoan vi la:\nb= % 1 Od", b); HoanVi(a,b);

printf("\nGta tri eua a sau khi hoan vi la:\na= %10d", a); printf("\nGia tri cua b sau khi hoan vi la:\nb= %10d·, b); getch{);

return 0;

}

void HoanVi(int a, int h) {

int tg; tg= a; a=b: b=tg;

}

41

C 11; u an g 2 'BltU THlJC

Mt)C TIEU en A CHUONG NAy·

};> Hieu klll'li niem vi hitll thuc trong ngon ngii lijp trink C.

};> Hitu va sudung thanh tlU;1O cdc phep todn trong ligon ngil C, eo thl hi/II d6'i m¢t bii'u thuc todn hoc thuang ggp thanl: bi!u (hue dung ma ligon ngil C eo ihE hii'u duac.

);> Hitu va su dung thanh thao cdc cdu true dieu Hie'" (wan ttl dieu khien) eua ngon ngil C.

2.1. KHAI NI~M

Bilu thuc HI. mot khai niem rAt quan trong va khong th~ thieu duoc ella bat kl mot ng6n ngtr lap trlnh nao dung de dien dar mot cong thuc, mot quy trmh tfnh toan . nao d6. Trong ngon ngu lap trlnh C, hila lhue duoc hieu la su ke't hop giila cac loan Iii va cac loan hf;mg thea mot trat t\l va mot 56 quy tae nhAt dinh nham dien dat mot cong thuc toan hoc nao day, Toan hang hi cac dai luqng rna eo mot gia tri xac dinh nao do. Trong ngon ngtr lap trinh C, 101m hang c6 the la cac bang, bien, phan tir mang va cac loi gQi ham rna co trii v~ mot gia tri C1,I the. COn loan la la cac thao tac XU Ii tren cac toan hq.ng theocac quy tic nhat dinh de dat duqe rnuc dich mong mu6n. Ng6n ngft lap trlnh C c6 hai Ioai toan tii, do la cac phep loan va cac loan tli diiu khiln. Cac phep toan chu yeu dung M xay dung len cac hilu thuc s6 hoc, bilu thuc quan h~ va logic. Con cac loan til diiu khiln dung de xay dung len cac kitu cau tnic co ban ella mot chirong trlnh may tinh (cdu true re nhdnh. va edit true l¢ip).

2.2. cAe TOAN TUTRONG NGON NGUL!P TRINH C 2.2.1. Cac Phep toan (cae phep xU Ii)

Trong ngon ngu l~p trinh C" cac phep roan rAt da dang va phong phu til cac phep toan 56 hoc, quan he va logic xu If tren cac kieu dir lieu da co cho d€n cac phep thao tac bit chi xu li du6'i dang cac bit nhi phan. Dac biet C eon dira them vao todn til dUu kien va cac chirc nang moi cho toan tu gan tao cho C co them nhirng tiern nang moi trong viec giai quyet cac bai toan thuc tc.

42

1. Cac phep toan so hoc

Cac phep toan s6 hoc la cac phep toan dung de viet cac cong thirc roan hoc,

bao g6m nhirng phep toan sau day: .

Bdng 2.1. Cac phep toan s6 hoc trong ngon ngtr lap trinh C

Ten phep toan Bi(fu dien Clurc nAng
Phep cqng BT1+BT2 (1.'\ Phep roan hai rrgoi dung d~ thuc hien cong gia tri clla
BTl voi BT2.
Phep IrU: BTl-BT2 Phep toan hai ngoi dung de thuchien phep trir gia tri cua
BTl choB1'2.
Ph€p nhan BTl *B1'2 Phep roan hai ngoi dung de thirc hien nhan gia tri cua
BTl voi B1'2.
Phep chia BTl/BT2 Phep roan hai ngoi dung de thirc hien phep chia gia tri
cua BTl cho BT2. Vci dieu kien B1'2 khac khOng.
Phep roan hai ngoi dung de thuc hien lay phan du cua
PMp lay phan du B11%B1'2 phep chia BTl cho BT2. Trong d6 BTl va B1'2 Iii. cac
bieu thirc nguyen.
Phep dOi dilu - BT Phep toan mot ngoi dung M dbi diu gia tri cua B1. cs« y:

- Neu phep chia thirc hien tren hai s6 nguyen rna so bi chia khong chia het

cho so chia thi ket qua nhan duoc se chi la phan nguyen cua phep cilia d6. Vf du:

10/358 c6 gia tri 18 3.

9/3 58 c6 gia tri 18 3.

D~ c6 the nhan diroc k€t qua dung cua phep 10/3 ta can c6 sir chuyen kieu

sang s6 tlurc (xem muc 2.2 .1. pluin 8) nhu sau:

(float) 1 0/3 58 eho k~t qua dung 18. 3.3333333 ...

_ Phep lay phan du chi co the thirc hien tren s6 nguyen rna thOi.

_ Ole phep +, ~ e6 cimg thu tv iru tien nhung nho han thu tv uu tien cua *, / va %. Ba phep toan nay lai co the tv nho han phep '_' (mi)t ngoi). Cac phep toan s6 hoc se duoc thirc hien tll trai qua phai va cac phep c6 thu tv uu tien cao han duqc thirc hien tnroc, cac phep c6 gia tri uu tien thlip han se diroc thirc hien sau.

2. Cac phep toan quan h¢

Cac phep toan quan he la cac phep toan dung de so sanh gia tri cua cac bi~u thuc voi nhau phuc VI,I cho viec ra cac quyet dinh trong chuang trlnh. Khac voi Pascal, cac phep toan quan he trong ngon ngtr lap trlnh C tra .ve gia trj 1 (tuang ung viti true) neu phep so sanh la dung, ngiroc lai tra ve gia tri 0 ttuang ung vai falsei.

IS BT l , BT2, BT co Iht Ia cac bitu thuc s6 h9C hoac bitu thuc quan he va logic.

43

J j ,

I

i I

I

!

Bang 2.2. cae pbep toan quan he thOng dung trong ngOn ngu lap trlnh C

Te.. pbiip BI~u dlen Chuc nAng Vidl;l
loan
Phep so sanh So sanh gia tri Clla BTl v6i BT2, n~u 3>6 co gm. trj O.
BTl> BT2 (1') BTl Ian han BT2 bitu thuc se tIi ve (10+2*3»3 cO
16nhan gia_ tfi I, nguqc I~ tra ve gia tri O. gia tri 1.
Phep so sanh So sanh giB. tri cua BTl v6"i BT2, neu 3<6 co gia tri I.
BTl <BT2 BTl nhc han 8T2 bieu thtic se tri ve 20+2<2 c6 giB.
nho bon gia tfi I, nguoc l\ii tra ve gia tri O. tri O.
Phepsosanh So sanh gia tri cua BTl v6i B12, neu 2+3==1+4 cho
BTl =81'2 BTl bang BT2 bi~u thuc se wi vt gia gia tri I.
bAng tf! I, ngucc 4i tra ve gm tri O.
Pbepso sinh So sinh gia tr] cua BTl voi 812, neu 3*(3+2) !:" 5
kbac(khOng BTl !=BT2 BTl kMc BT2 bi~u thuc se wi vt gia cho gia Hi I.
bang) tri I, nguqc Iai Ini vt gia tri O.
Ph~p so sanh So saM gia tri cua BTl voi BT2, neu 10+3*5>=7 cho
BTl 100 hon hay bang BT2 bi~u thuc gia tri 1.
ton hen h04c BTl >=B1'2 sf! tra vt gm Iii l, nguoc lai tni. vt gia 20>=20 cho gia
bang lei o. tr] I.
Ptu!p so sanh So sanh gia trj cua BTL v6i BT2, neu (a+b)*(c+d)<=12
BTl nho hen hay bAng BT2 bitu thuc vCri a. b, c va d !.ir
nho han hoac BTl <== BT2 se tra vt gm tr] I, nglU,"lC I~i Ira ve giB. lllQt la 1, 3, 5 va J
bang tr] O. se co gia lei O. Chuj:

- B6n phep d1u e6 cung thu nr UU tien, hai phep sau cling co cung thti tu uu

tien nhung tMp han b6n phep cUu tien,

- Cac phep toan quan ~ c6 thu tl! uu tien nM han cac phep toan s6 hQC.

- MQt bil!u thue quan h¢ chi c6 thi co gia tri 1 (dung) hoac 0 (sai).

Vi dI;l2-1. Xet bieu thue quan h¢ e == a+b>=c+d thl phep a+b dircc thuc hi~n tnr&: tien sau do dc!n phep c+d, tie'p theo kc!t qua cua hai phep cong se ducc so sanh v6i nhau thong qua phep so sanh '> ='. Cu6i cung gia tq ella e moi duqe so sanh v6i. kc!t qua vira nh~ duqc trong phep so sanh '>=' thong qua phep so sanh '=='. Kc!t qua nay chinh Ia kc!t qua cuoi cung ella bieu thucquan he vira xet,

3. Cae phep loan logic

Cac phep roan logic Ja cac phep roan thuong dung ktl hop voi cac phep quan h¢ d~ XAy dl}ng Jtn cac bi'u thuc quan h~ va logic. Bh~u thuc quan he va logic la bi~u mue chi e6 gia tri 1 (dung) hoac 0 (sai) nhu vi du 2-1. Trong ngon ngi1l~p trlnh C co ba phep roan logic thong dung la phep phil dill" m(jt Ilgoi, phep "(ii va pilip hoac, ChUc nang va each bieu dien ella clning diroc mo fa trong bang 2.3.

16 BTl va BT2 ciing c6 chi la cac Ilit"i:u rhrrc s6 hoc hoac bi~u th(rc quan h~ va logic.

44

Bang 23. Cic pMp tOOR logic tb6ng ~g trong ng6n ngi LW trmh C

nn phep Bliu dim CbUenAng Vid¥
toan
Phep phu N~u BT 00 gm tri khk 0 se cho gm tIl o. 1 (2+5) cho
dinh mot ! BT Neu BT co gia tri bang 0 sf cho gia rrit. gii tri O.
ngoi
Phep hoi Neu BTl bang 0 va BTI bang 0 se cho gi! tr] 0 0&& (2+3)
N~u BTl bang 0 va BTI kluk 0 sf cho gili tri 0 cho gii tri 0
(phep BTl &&BT2 Neu BTl kMc 0 va BT2 bing 0 se cho gia tn 0 (2+6) && s
AND) N~u BTl kMc 0 va B'r2 khac 0 se cho gm tri 1 c no gili tri 1
Neu BTl boing 0 va BTI bing 0 se cho gUi tri 0 o II (5-5) cho
Phep hoac BTIIIBT2 Neu BTl bang 0 va BT2 kMc 0 se cho gm tri I gUi tri 0
(phep Ok) N~u BTl kluic 0 va BT2 bang 0 ss cho gi! tri I 011 (10+3)
Neu BTl kluu: 0 va BT2 khcic 0 se cho gm tri I cho giii tri 1 ChIlY:

Phep phu dinh mot ngoi '!' co mire uu tien eao hon cac phep quan he va s6 hoc, nhirng cac phep luJi va phep hofj.c lai co rmrc uu tiea thAp hon cac phep toan quan he txem them muc to s« bilt them vi' thu tt! uu tien cUa cae phep todn).

4. Cdc phip thao tac bit

DAy la cac thao me thuong hay dUng trong hW ngit (ngO" ngil Assembly).

Trong ng6n ngii' l~p trinh C cac phep thao tac bit chi tiln banh xu 11 tren tim.g IRl nhi phan cua mot s6 nguyen tkhong dung cho st/ thuc) va dOi khi chting duqc sir dung nrong d6i hiru dung. Cac phep thao mc Bit bao g6m:

Phep toan Y nghia Vi dl,l

& Ph9p AND thee Bit x&y

I Phep OR theo Bit xlY

" ?hep XOR x"y

« Phep d!ch trai a«4

» Phep djch phai a»4

·Pnepd"ao Bit -x (11)

BdRg 2.4. Hoat d¢ng rea cae phep thao me bit trong ngOn age I~ tl"lnb C

1&1 bing 1 lit bang 1 1"1 bing 0 n bAAg 0
1&0 boingO 110 bAng 1 l"Obang I 10 blng 1
0&1 bang 0 011 bang 1 0"1 bing I a-cen bAng a"'2"
0&0 bang 0 010 bang 0 ()II() bang 0 a»n bing a{2." Chuj:

an phan bier cac phep thao tac Bit' &', 'I', '!' vOi cae pbep '&&', 'II' va '-'.

Vi du voi bien nguyen a=OxOfff (gia tri 4095 trong he th~p phan) va biM nguyen b=OxOOff (co gia tri 255 trong h¢ th$p phan) thi:

a&&b cho kAt qua 1 a&b cho ·kft qua OxOO",

17 x,y La cac Bit nhi phan cua m¢1 bi!"n nguyen, a la m()tbien nguy~n. HI, 8f 1, 8f2 ding co 1M la cac bieu thirc sO hoc hoac bieu !hue quan he V'::' logic.

45

allbcho kat'qu8 1

la cho k~t qua OxfOOO lb cho k€t qua OxffOO

alb cho kat qua OxOfff

-a cho kat qua OxfO01(-4095)

-b cho kat qua Oxff01 (-255)

Vi dlJ. 2-2. De trich byte thap va byte cao ciia mot bien nguyen a ta c6 the lam nhir sau: '

LowByte=a&OxOOff; I"nlra cao cua a sa chi c6 gia tr] 0, nlta. tM'p sa giG' nguyen gia tr] cua n6*/

H ighByte=a »8;

printf("\nGia tri eua Byte cao la: %x",HighByte); printf("\nGia tri cua Byte thap la: %x",LowByte);

Vi dlJ. 2-3. D€ kiem tra Bit thu 6 cua mot s6 nguyen a bang hay khac 0 fa co the tien hanh theo hai each nhu sau:

- Cach 1:

b=a»6;I"£kfa Bit thii 6 cua bien a ve vi trf Bit 1 */ if(Ox01 &b)

printf("\nKhac khong");

else

printW\nBang khong");

- Clich 2: Thiet l~p m(it na Bit nhu sau: if(Ox0040&a)I*Neu bit 6 khac 0*/ printf("\nKhae khong");

else

printf("\nBang khong"); 5. Clic phep tling / gidm

Cac phep tang (giam) Ia cac phep toan mot ngoi trang ngon ngir lap trinh C dung d~ tang (giarn) cac bien (nguyen hoac thirc) len (xu6ng) 1 gia tri. Bao g6m cac phep sau day;

Bang 2.5. Cac phep tang / giam trong ngon ngu lap trlnh C

Ten phep toan BMu dl~n Chllc nang
Phep tang (moc ++i (18) Sau khi thl,l'c hien cau I¢nh gia tfi cua i lang len 1
Phep tang sau i++ Sau khi Ihl,l'c hien cau lenh gia tr] cua i tang len I
Phep giam rnroc --i Sau khi thuc hien cau lenh ghi lei ciia i giam di 1
Phep giam sau i-- Sau khi tlnrc hien cau lenh gia tr] cua i giam di I Chuy:

- am phan biet SI! khac nhau giua viec tang tnroc va tang sau (ciing nhu gidm truac va gidm saul. Trong phep tang sau (gidm sau) thl bien i tang (gidm) sau khi gia tri ella n6 da duoc SU dung, Nguoc lai, trang phep tang tnroc (gidm truce) thl bien i tang (gidm) tnroc khi gia tri cua no da diroc sir dung, COn ke't qua thuc hien eiia cac phep toan tren thi hoan toan giong nhau,

Vi du 2-4. Xet hai doan chuang trinh sau:

int i=10, x; int i=10, x;

1M i la mot bien nguyen hoac thuc.

46

x=i++;

x 58 c6 gia tr] la 10; con i 58 c6 gia tri Ia 11

x=++i;

x 58 co gia tri la 11; con j 58 co gia tr] 1ft 11

• Khong nen sirdung cac phep tang giam qua my tien trong cac bieu thli'e vi eo th~ se dAn d€n cac k€t qua sai khong mong muon.

6. Phep Itty dia chi va kich thuoc hii'n .

Cluing ta dii. bier rang, rnci bien sau khi khai bao se diroc cap phat mot vung nho gom mot s6 Byte lien tiep (so' luang cae Byte phu thuoc va~ loai bir/n). Dia chi ella Byte nho dau tien trong b¢ nho se diroc coi HI dia chi ella bien do. D~ truy nhap den vung nh6' cua bien ta co th~ truy nhap thong qua ten bien. nhirng doi khi hilt buoc ta phai truy nh~p thong qua dia chi cua bien (vi du nhu trong cdu /¢Ilh scanfy. Muon biet duoc dia chi cua mot bien x nao d6 trong bQ nho ta e6 tM viet &x.

Khi mu6n bietklch rhuoc (tinh theo Byte} ella mot bien hay mot kieu du lieu

ta e6 the.dung toan til sizeof tuec: ell phap nhtr sau:

5izeof(KiEfu_d[j_'i~u); (1t)

hoac sizeof(Teo_bien);

Vi d~ 2·5. each dung toan tir sizeof. D~ xac dinh s6 phan nr n cua mot rnang A tro~~ co eh€lchiri dau ta lam nhir sau:

double AU={10., 69.3,39.4};

int n=sizeof(A)/5izeof(double);

7. Phep gdn va bilu thftc

. Phep gao fa phep dung d~ dUB:. gia tri cua mot biSp. thirc nao d6 vao trong mot

bien nrong thfch theo cuphap nhu sau: , '_ _

Bien=BT;

Tnroc tien, may se tien hanh tinh gia tri cua bidu thee BT. sau d6 moi gan gia tri tinh dU'I;JC cho bIen Bien (do mire uu tien cua toan til gan gan nhu thap nhat, chi cao han tom til ','. Xem them 2.2.1. mucIth..

Vi du 2-6. Xet doan chuong trinh sau: float a, b=3.5;

a=b''(b-t.s)» 1 0;

Ket qua tfnh roan cua bieu thuc b*( b-1.5 ) + lOse duoc gan eho bien a (17). Xet doan chirong trmh sau:

float x, y, z, a, b;

a=b=1999;

z=(y=3)"(x=10);

19 Kieu dl1 lieu c6 tM 130 kieu chuan nhu int, float, ... hoac 130 cac ki~u tu dinh nghia,

47

K8. qua II bie'n a va bitn b duqc gan dang mot gia tri la 1999, con bien x dUqc gao gia hi 10, bi6n y dllqC gao git tri 3 va k€t qua CUd phep tinh 3* 10 S115 duqc gan cho bi~n z.

D6i vOi n# 56 pRep gan ~ b$ rna bi€n duqc gan c6 m~t ca trong hai vl cita ~\I lhac gall, vi d" rum:

int i,j,k; i=i+2; j=j·1 ; k=k"(i+j);

06 tM ~ "gin han nhU' sau

i+=2; j·=1 ; k"=i+j;

Chuj:

· do phan biet phep gan '=' voi dau dAng thirc trong toan h9C.

• Kitu ciia bieu thee HI' b tren phai tuang thleh v6i ki!u cua bien dugc gan gia trio Neu S1,l nrong thich nay khong thoa man thl chuang trlnh S115 phat sinh mot 16i. 51! tuong thfch b day e6 nghia la kieu cua bitu thlic BT c6 the duoc chuyen d6i rt1¢t each 11.1' dQng sang kieu eua bi€n gan thea nguyen tAc kieu int c6 tM chuyen thanh kieu float, kieu float c6 the chuyen thanh kitu int bang each ch~t c1,11 phaa thap phdn, kieu double co the chuyen thanh kic~u float bang each lam. tron, kieu long c6 the chuyen thanh kieu int bang each cAt bo mQt vai chu s6 ...

· D6i voidang vilt ngin c6 thi ap ~ng cho cac phep toe ill S(fJulC va cac phep thao tdc Bit Ita; ng6i nhu +, ., *.1, %, «, », &, f\ va I. Vi du M gan s6 du cua phep chia a cho b ta c6th! vi€t nlnr sau: ao/o=b; khi d6 a S115 chira s6 du c~n tim. Hoac di x6a bien nguyene v~ khOngtac6 tM vilt e"=e;

8. CluI,e;' d6i kiiu gm tri trong cdc bilu tIuIc

Viec chuyen kit~u thueng xiy fa troo.g cac tnroag hop: hoac bieu thU'c g6m cac toan ~ kHac ki~, "* gan cae d6i tm;ntg idlac kieu chonhau, hoac truyen tham s6 khac kieu cho cac ham va trs. v~ gia tri khac kieu bang cau lenh return. Vi¢e chuyen ~ nay .en 06 the ti!n kaoh t .. ~g th'i se tutn thea so d6 sau:

Char ·>illt->1ong·>ftoat·>double·>!ong double

C6 nghia IA ntu hai toan hang trong m<>t pbep toan c6 kieu khac nhau thl ki!u ~ hau (co p~ vi nIu3 hun) se ~ nbg thanh ki~u cao rum cho pbUbQp v(ri roan hang kia tnrC1c khi pbep Wln.dugc tiM hanb xii' Ii.

Vi d(42·7. Khi thuc hi¢n cac phep tfnh sau: 1.5"(1113) sidlott:~ qua Ii 4.5 (ki~u float) 1.5·11/3 sl cho k& qua 13 5.5 (ki6u float)

Trang nhOng tnrong hI;Jp ta mu6n.dibl khi!n qua trlnh chuytn Mi thea y mlnh thl c6 the dUng mQt ph6p thao lAc ,,*e ~t MIa phep ep leilu.

Phep ep Ideu La pb.ep dUng dtcbuy&t d6i gia tri ella mQt bieu thuc til kiiu nay sangkilu khac theocai d·jnh Cl;J t:ti. CU phap cua phep ep kieu nhu sau:

(Kitfu) '8T;

Trong d6 Kilu la ki~u Cb chu.~n ,&n, Bf la bitu thUe cAn duqc chuyen rhanh Kitu thea nhtlng nguyen tlcnbu d6i vOi vi¢e chuytn d6i ur d¢ng. Vi du cau I¢nb (int}(10.3) se cho k~t qua la 1'0.

48

Chuj:

- Phep ep ki~u khong lam thay d6i kieu va gia tri cua chinh ban than bien bi ep kieu, Vi du neu a la mot bien ki~ufloat thi sau phep (int) a thi a va.n la bien ki~u float nhung (int) a lai c6 gia tri kieu so nguyen.

- Dt chuyen d6i gia tri thuc sang gia trj nguyen, nen dung (int)(8T +0.5).

- Trong qua trlnh chuyen d6i can chu y den thu nr uu tien cua cac phep toano

Vi du xet hai bieu thuc sau:

. (int)1.6*100 se cho kat qua la 100 . (int)(1.6*100) se cho kat qua I<!.I 160

9. Toan Iii die'll ki~n

Ngon ngtr lap trlnh C dua them vao mot toan lU moi co dang cu phap nhu sau:

E1?E2:E3 ;

Trang d6 toan nr ?: dtroc goi la roan tiI dieu kien, COn E1, £2 va E3 la cac bieu thuc nao d6. Sl! ket hop cua toan tir dieu kien va cac bieu thirc £1. £2 va £3 tao thanh mot bieu tlnrc moi co ten la bilu tht« voi todn ttt die'u ki¢1I (20). Gia tri cua bieu thirc nay se bing gia tri cua £2 neu £1 co gia tri khac khong (£1 dung), hoac bang gia tri cua £3 neu gia tri cua £1 bang khong (£1 sai). Kic."!u cua bieu thirc voi toan til ditu kien la kieu cao nhat trong cac kieu cua £2 va £3 ttlieo sa do' 0- m,!c 2.2.1. phdn 8).

Chuy:

- £1 khong nhat thiet phai 1a mot bieu thuc quan he va logic ich] co gid tri O=sai va 1 =dUllg) rna co the la mot bieu thirc bat ki.

- Bieu thirc voi roan til dieu kien rat tien loi trong viec tao ra cac Macro lam cho chuang trinh rnern deo han.

Vi d". 2·8. De tim so Ion nhat trong hai s6 ta co the viet nhu sau:

#include "stdlo.h" #include "conio.h"

#define Max(A,8) (A»(8)?(A):(8)

1* .***.**************~********~***~****~***~~****~****~***************~*******************. *'

int main'O {

int x=10, y=65;

long a=3478925, b=2345677; float c=2.4, d=4. 7;

printf("\nSo Ion nhat trong hai so x, y la: %10d", Max(x,Y»; printf(M\nSo Ion nhat trong hal so a, b la: %10Id", Max(a,b)); printW\nSo Ion nhat trong hal so c, d la: %10.2f', Max(c,d)); getchO;

return 0;

}

:Ie Trong mot s6 such thuong goi day [ii. bieu thirc dieu kien. Tuy nhien each goi nay co Ih~ gay cho nguo! hoc, d~e biet Iii nhtmg nguoi dii hoc qua ngon ngCi" Pascal. mot .'it! nham Ian v6i cac bieu thrrc dieu kien duoc sir dung I rong cac toa II IiI d ieu khien nh u i r ... else, while ...

49

~NNlTC

«« qud chay chuang trinh nhu sew:

Solon nhat trong hai so x, y la: 65

S6 Ion nhat trong hai so a, b la: 3478925

S6 Ion nhat !rong hai so c. d la: 4.70

I~ ***w*****~**.***~*.**** •• **********~r******~~~*.~*~~**********.~~*****.**.*****.********. -,

Ta nhan thay ding, ncu ta viet chuang trinh nay duoi dang ham. thi ta dn pluii c6 3 ham kluic nhau (clio 3 kh'll eli? li~1I kInk IIIUlIl hI int, float WI long) lam cung mot nhiern vu la tim ra so e6 gi,\ tri I&n han rrong hai so. Dieu nay that bat tien eho vice ];{p trinh,

Vi d~ 2-9. Trang ngon ngLr lap trinh C. dd tim gia trj tuyet doi ella mot so ta co :I ham khac nhau e6 ten nhu sau:

f)g tim gia tr] tuyet d6i cua mot 56 nguyen x ta dung ham;

int abs(int x), ham nay dUqe khai bao trong thu vi~n stdlib.h f)e tim gi8 tri tuyet doi cua mot so truro y ta dung ham:

double fabs(double y), ham nay I~i dU'<;1e khai baa trong math.h f)~!lm gia tr] tUY$1 doi cua mot so nguyen dai b ta lal dung ham:

long labs(long b), ham nay dU'l1e khai baa trong stdlib.h

DJy qua thirc 1<1 mot dieu het sere phi IY. VI cung mot chirc nang ta lai phai dung den 3 ham khac nhau, duoc khai baa trong cac thu vien khac nhau. BAng each viet Macro, ta co the: viet lai ham tinh tri tuyet doi nhu sau cho cac ki~u du lieu:

#include "stdio.h" #include "conio.h"

#define Abs(A) (A»=O?(A):-(A)

int mainO {

int a=-1 0;

long b= 1234567; float e=· 6.7;

printf("\nTri tuyet doi eua so ala: %10d",Abs(a)); printf("\n Tri tuyet doi eua so b la: % 1 OJd~ ,Abs(b»; prinlf("\nTri tuyel doi eua so c la: %10.2f".Abs(c)); getch():

return O~

/* ****~~.******~*******~*******~*************.***~****.***~**~*******************.*.** •• ~** *'

Kef qua chay chuang trinh:

Tri tuyet doi eua so ala:

Tri tuyet doi eua so b la:

Tri tuyet doi cua so cia:

10 1234567 6.70

Viec dung toan nr dieu kien d~ viet cac Macro tuy co nhieu lIU diem nhirng chi nen ap dung cho cac thao tac nrong d6i dan gian. Doi voi cac thao tac phirc tap, ta van nen viet chuang trinh diroi dang cac ham (dllr(lng -4 se d(;' cdp dell Will de" /ldy) de' giarn kich thiroc cua chuang trinh, tuy nhien trong twang hop nay 16c do cua chuang trlnh se bi cham di (I'i~c Ii gidi dJ/~1(, xem nhubai tdp),

50

10. Thir t~ uu tien ella cdc phep toan

Tlnr ur uu tien ella cac phcp toan Iii mot van d~ het sue quart trong, trong bicu there bao gia cac phep toan co thtr tl.r tru lien cao hall cung diroc thuc hien tnroc va nguoc lai. Bang 2.6. se Icing ket ther It! UU lien cua de phep toiin trong ngon ngfr C.

Being 2,6. Thir tI! uu tien ella cac phep toan trong ngon ngil' I~p trlnh C

Mile IlU lien Cac tuan III Tlur III ket hup
I () n -> Tuii qua phai
! ~ • (phep doi dau) ++ _. & (dung de' Jay diu chi cua
2 bien) '" (dung de khai bao con tro xet trong chuong 3) () Phai qua trai
(phep ep kieu) vii SiZl'Of
3 '" (phe p nhan) f % TrM qua phai
4 + • (phep trir) Trai qua phui
5 « » Triii qua phai
6 < <= > >= Tnii qua phai
7 -- != Trai qua phai
8 & (phep ihao Hie bit AND) Trai qua phui
9 " Trai qua phai
10 I Tnii qua phai
II && Trai qua phai
12 II Tnii qua phai
13 ?: Phai qua tnii
14 = += -= "'= f= %= «= »= &= "= 1= Phai qua tnii
15 , T rUi qua phai Trong do, cac phep loon tren mot dong co ding thu ur iru lien. tuy nhien trat nr ket hop cua chung lai khac nhau (co tlu/ fir fuji (ilta pluli hot!c IIg/t{tc 1~/i). Cac phep toan o dong tren co thu tl! uu tien eao han cac phep 100In d dong diroi. Mere uu tien cao nhst lit cac phep loan: '0' dung M viet cac bie"u thuc, '[]' dung d& truy nhap cac phan tii mang, '->' dimg·M truy nhap thanh phan cau tnic thong qua con tro (xem chuang 3) va phep '.' dung M truy nhap cac thanh phan cau true thong qua bien. Mire uu tien thap nMt lit roan tii '.' dung M phan tach cac bien khi khai baa. phan tach danh sach d6i trong cac ham ...

Chitj:

Neu kh6ng nho thti nr uu tien ella cac phep loan, ta nen sil dung dau ngoac

tron '()' d~ viet cac bi~u there.

Vi du 2·10. Khi viet bieu [hue: a>b?a:x?y:z Ta co the" viet ro han nhir sau: a>b?a:(x?y:z)

11. M(U so' vi du minh hoa

Vi du 2-11. Hay viet chuang trinh tinh gia tri cua bien thuc sail roi dua ke{

" an hi h (x + Y 5) 4 4 3 2 ,. I' - . , . h

qua ra man III : -- + 3.x 10+S.x - .x + 12.x -6.x +93 \'01 .v, V a cac ara rri n up

20 - ~'"

llr ban phfm.

Gidi: Trong ngon ngil' J~p trinh C d~ unh tiL(( it· y" ta 'ill dung ham:

double powidouble y, double x) khai bao trong nuuhI: (Will IJIlI.l ltu III de' bier them cac Ill/III kluic Clla Turbo ( '),

s:

I*******·***********·***··********~******·***************** •• ****~~***~.*.****.********.*** */

#include "stdic.h" #include "conlo.h" #include "math.h"

int mainO {

float x,y; double z;

printW\nHay nhap gia trl cho cae 50 x, y:\n"); scanf("%f%f" ,&x, &y);

z=( ((x+y)/20+3*pow(x, 5))* 1 0+5"pow(x, 4)-4" pow(x, 3)+ 12"pow(x, 2)-6*x+93); printf("\nGia tri cua bieu thuc can tinh la: %10.41",z);

getehO;

return 0;

}

Kit qua cht.ly chuang trinh:

Hay nhap gia tri cho cae 50 x, y: 3 2

Gia tri cua bieu thue can tinh la: 7772.5000

/* ~******.**************************.****** •• ***********.****.************.****~*~********* */

Nhan xet:

Chuang trlnh tren eo su- dung ham pow() de tinh cac bieu tlnrc dang luy thira, Tuy nhien ham nay sir dung cac d6i la cac bien kieu double va gia tri tra ve ciing la kieu double. Do d6, trong chtrong trinh tren khi ta khai bao cac bien x.y la cac bien kieu float thi chuong trinh se tu dong chuyen cac gia tri d6 sang kieu double. Ket qua eu6i cung cua bi€u thirc cung e6 kieu la double.

Vi du 2-12. UP chuong trlnh doc nr ban phfm dQ dai ba canh cua tam giac ABC roi tinh dien tfch va cac duong eao ella tam giac d6 (chuang triuh khong cdn kie'm tra diiu kien dt hinli thanh tam giiic).

Gidi: Df tfnh duqe di¢n tich cua tam giac ta su- dung cong thirc Herong sau:

S = JP(P - a)(P - b)(P - c) trong do P la mra ehu vi va a, b, c la dQ dai nrong ling voi cac canh cua tam giac, ~ tinh duoc can bac hai ella mot s6 x nao d6 ta sir dung ham double sqrtidouble x) khai bao trong math.h,

1* ***~**********~*~* •• *************************~************ •• *****~~******.*******~******* */

#include "stdlo.h" #include "conio.h" #incliJde "rnath.h"

/* ****************************.******************************~****.**********.**********~** ~I

int rnalru) {

float a, b, c, P;

double Ha, Hb, He, S;

printf("\nChuong trinh tinh dien tlch va duong cao cua tam giac~); printf("\nHay nhap do dai ba canh a, b, c.m"):

52

scanW%f%f%f', &a, &b, &c); P=(a+b+c)/2; S=sqrt(P"{P-a)"(P-b)*( P-c»; Ha=2"S/a;

Hb=2"S/b;

Hc=2"S/c;

printfnnDien tich cue tam giac ABC co cac canh\na= 10.2f\nb=%10.2f\ \nc= %10.2f \nla: %10.2f", a, b, c, S);

printf("\nCac duong cao tuong ung la:\nHa= % 1 0.2f\nHb= % 1 0.2f\nHc=\ %10.2f", Ha, Hb, He):

getch{):

return 0;

}

/* **.***~~*******~**~**.********.~*********~********.******.**~~*******~**************** •• * */

Kit qua chay chuang trinh:

Chuong trinh tinh dien tich va duong cao cua tam giae Hay nhap do dai ba eanh a, b, e:

745

Dien tieh eua tam giae ABC co cae eanh

a= 7.00

b= 4.00

e= 5.00

1<':1: 9.80

Cae duong eao luong ung la:

Ha= 2.80

Hb= 4.90

He= 3.92

Vi dlJ. 2-13. Lap chuang trmh tinh va in gill tri bieu thirc sau day ra man hlnh:

3sin2(2x+1)+2eos(3x+2) ,. l' i th h 'b' hf

y = 2 val x a mot so t uc n ~p tu an p rm.

Gidi: D~ tfnh diroc gia tri cua bieu tlnrc ta can sir dung cac ham thu vien double costdouble x) va double sinidouble x) diroc khai bao trong math.h.

/*-************* •• *************************.********** •• **~***********~***********~* •• ***** ~I

#include "stdio.h" #include "conio.h" #include "rnath.h"

int mainO (

float x: double Y;

printf("\nHay nhap gia tri eua x:\n"); seanf("%f" ,&x);

Y=(3*pow{sin{2*x+ 1 ),2)+2"eos(3"x+2»/2; prinlW\nGia tri eua bieu thue la: %10.4f",Y); getehO;

return 0;

}

53

Kef qua chay chuang trinh:

Hay nhap gia tri cua x: 20.3

Gia tri cua bieu thuc la:

1.7085

/* ~.**~*******.**.*~~~~~*********~****~*****.*~*********.******** •••• *~~~* •• *************** */

2.2.2. Cac toan nr dleu khlen

Trang lap trlnh c6 cau true, m6i chuang trinh baa gem nhieu diu Ienh diroc tlurc hien mot each tuan ur thea tlur tV rna cluing diroc viet (ni'll trtu: tudn I{I). Tuy nhien trang hau het cac tnrong hop fa can dieu khien thu nr thuc hien cac call lenh thea mot trat ur nao do d~ co the giai quyet dtroc cac van de d~t ra. Cong cu giup cho lap trinh vien co the Jilin diroc dieu nay ehinh Ia cac toan tii dieu khien, Cac toan tir dieu khien trong ngon ngir lap trlnh C thirc chat la cac lenh cua ngon ngil dung d~ t6 chirc ra cac loai call true trong chuang trinh (aill true /(Ip.'i'e nluinh). Ve m~11 cong dung c6 Ih~ chin c.ic roan til dieu khien thanh .J nhom chfnh:

- l.enh nhay kh6ng dieu ki$n

- Nh6m cac lenh re nhanh

- Nh6m CaG I$nh dung d~ t& chuc chu trlnh

- Nh6m cac I$nh dieu khien knac.

J. Lenh nhciy khong dieu kif"

La cau lenh dung de' be gay unh twin h,r cua mot chuang trlnh vil!( bang ngon ngir lap trinh C, n6 c6 cu phap nhu sau:

gato Nhan;

Trong do, NI/(JII la mot ten co dau ':" dung sau dung de: gan cho bat ki mot cau lcnh nao trong chuang trinh. Vi du: Tiep: ++i; thl Tiep la nluin cua cua cau lenh ++i.

Khi gap loan tii nay may se nhay tai cau lenh co nhan viet sau tir kh6a goto bo qua cac cau lenh dung tnroc boac dung sau lenh nhay nay.

Chuy:

- Call Ienh goto va nhan Nhan phai nam trong cung mot ham (J:.luJlIg (hi dung de'll//{iy flr lunn ua» sang lit/III khac).

- Khong tht dung toan tir goto de: nhay tu ngoai vao trong mot kh6i lenh.

Nhung viec nhay nr (rang ra ngoai mot khoi lcnh lai hoan roan hop 1¢,

- Trang chuang trinh han chc dung toan tir goto VI no pha va tinh call true cua chuang trlnh,

2. Nhom cac lenh re- nhanh

La nh6m cac lenh dung d~ ra cac quyet dinh r~ nluinh, nhay toi tlurc hien mot cau lenh (kl/(/'j /fllll) nao do trong chuong trinh dira vao giit tri tlurc te cua mot bieu thirc nao do.

a) rsa« ttl if

La toan f/( qllYlj; diul: hai lua .11911 tuy thuoc vao gia tr! bang khong (sai) hay khat khong (dlil/g) Clla l>i('11 IM(e va co ell phap nhu sau:

54

D"mg 1

if ( Bieil tlutc ) Cdll_Nnll;

D(;lIlg 2

if( Bi /11 f III(e) Cdu_ffllflJ :

else

cu« j:

- Bilu thuc eo the la bieu thirc bat kl (B!eu thiic nguyen, thuc. quan he va logic, ... ) mien sao ClT tni. ve hoac gia tri bang khong (Ii'lg voi fI'l(()Hg hop :;lli) hO{IC gia tri khac kh6ng (I(ng vai tn(('mg lI(ip dllng).

- Tai vi tri cua Cau_l¢nh neu dn thuc hien nhieu cau lcnh ta phai dua cluing vao troug khoi lenh.

- Khi viet chuang trlnh, d€ tien cho viec go roi ta nen viet sao eho cac diu lenh va khci lenh cung cap nen nam tren mot cot (fIning (,(If), diem dau va diem cuci cua mot khci lenh cling nen thang C9t.

.. Bilu tlU(C baa gio cling phai diroc dat trong hai dau '()'. - Tnroc [lr kh6a else van phai c6 dau ';'

Hoar dong cua loan Ilf if co the' diroc mo ta bang so do sau:

D(II/I! 2

Sai

/ lilill 2./. SCJ d6 hnat dl'lng ella ioan ur i r.

- Cac loan IU if co the' long nhuu, tuy nhien khi so lCT khoa else Ir han so' tiT khoa ifthl rir kh6a else sc dtroc g.-in voi ifg,tn nhat tnnrc do,

Vi du 2~14, Vat doan chuong trinh Situ:

jf (a>O)

if (b>O) c=2003;

else

c=1999;

Thi else se duoc g:'tl1 voi ur khou iJbcn durri. De tninh nluim \{1Il trang khi SlT dung de roan Itr if Icing uhau ta ncn Slf dung khoi lenh M xac dinh pharn vi cho tirng roan t lr if trong ell uong trlnh. V i d 1.1 tren co Ihe: vier lai nh lC sau:

55

if(a>O) {

if(b>O) c=2003;

else

c=1999;

}

Vi d~ 2-15. Lap chuong trinh de may tfnh noi chuyen voi ngiroi. May "noi" bang cac cau hien tren man hinh, ngiroi "noi" bang each go (u ban phim. Noi dung cuoc tro chuyen nlur sau:

May hoi ban tsn, giei tfnh, co gia d1nh chua? Neu chua thi may khuyen ban "Hay can dam va than trQng! Chuc ban (ten) nhieu may man I". Neu ban c6 rai thi may hoi xem co may can. Neu nhieu han hal can thi may n6i ~C6 ve hoi nhieu rai day~. Neu tren narn can thl may n6i "Qua nhieu rai anh (c6) ban cua t6i oi l",

Gidi: D~ c6 th~ viet dUQ'C chuang trinh nay cluing ta can sir dung cac bam xu Ii chuoi duoc khai bao trong thu vien string.h va stdlib.h cua Turbo C sau day (cae ham kluic co (lui xem them trong pli« luc /If):

in! strcmpi(char *s1, char *s2) dung de so sanh hai chuoi, khong phan biet

chtt hoa va chir thtrong, bam cho:

- Gia tr] am lieu chuoi sl 11110 hun chuoi s2

- Gid tri Hong neu chuoi sl bang chuoi s2

- Gia tri duong nell chuoi sl lou han chuoi s2

int atoi(char *s) dung dci chuyen chuoi s sang gia tri nguyen. Ham nay khai bao trong stdlib.h,

/* ** •• *.*******~ •• * •• * •• ***************.*.*****~***~***** •• **.****~**.****.***~***.**** •• *~ ./

#include "stdio.h" #include "conio.h" #include "string.h" #include "stdlib.h"

int mainO

{ char GioiTinh[3], Ten[251, Traloi[20]; printf("\nXin chao, ban ten la gi ?\n~); gets(Ten);

printW\nChao ban %s, ban la nam hay nu(Nam/Nu) ?\n", Ten); gets( GioiTin h);

Hoilai:

printf("\n8an co gia dinh chua ?\n~); gets(Traloi);

if (strcmpi(Traloi,nRoi")==O)

( printf("\nBan da co may con roi ?\n");

scanf("%s" .Tral.oi); r nhap dllei danq chuoi ki tu rai chuyen thanh so*1 if(atoi(Traloi»=5)

{ if( strcmpi (G ioiTinh, HN amn)==D)

printW\nQua nhieu roi anh ban %s cua toi oi I", Ten); else

printf("\nQua nhieu roi co ban %s cua to; ol l", Ten);

56

}

else if (atoi(TraLoi»=3)

printf("\nCo ve hoi nhieu roi day!");

}

else

{ if (strcmpi(TraLoi,"Chua")==O)

printf("\nSan nen can dam va than trong! Chuc Ten);

else {

%s may man han!",

printf("\nSan nen go lai haac \"Roi\" hoac \"Chua\""); goto HoiLai;

}

} getchO; return 0;

}

Kef qua ch~y chuang trinh:

Xin chao, ban ten la gi ? Sinh

Chao ban Sinh, ban la narn hay nu (Nam/Nu) ? Nam

Ban c6 gia dinh chua? Roi

Ban co may can roi ? 5

Qua nhieu roi anh ban Binh cua toi oil

b) Todn til if miT r~ng cho n Iva chon

Cu phap va nguyen tae hoat dong nhu sau: if(Biliu thCtc 1}

Cau_l~nh1; else if(Bieu thuc 2) Cau_l.nh2; else if(Bieu thCtc 3) Cau_l(mh3;

Cau_l~nh n+1;

else if(Bieu thuc n) Cau_l~nh n;

else

llinh 2.2. So do hoat d¢lIg dli\ loan tIt if rntr rong cho 11 lJ lfCrng hop

57

Chuy:

- Tai vj trf eric Ccill_I~llh i neu ta muon tlurc hien nhieu Ienh rhi phai d<).1 cluing trong khoi I¢nh.

- Cic Well thuc chroc slr dung c Ling co Ih~ Iii mot bicu thirc bat kl co gia tri btlllg khong (Illig voi (n(("',g Iwp sui) hO~IC kh.ic khong (/(lIg \'(Ij (U(r'tng h(fP (!lillg).

- Trang s,S n+I luu chon chi co 1116! hra chon duy I1hJt rna thoa man mot 1lie"1l th uc i uao d6 Iii diroc thuc hien, Nell {fii ca II Biiu thuc deu khong thoa rniin tlu Ccill._l~fl" fl+/ diroc thirc hicn va cau lenh nay cilng c6 th~ vang mat.

Vi du 2-/6. Vie"! chuang trinh giao ticp voi may tinh, may tinh hoi gioi tinh, tuo: cua ngiroi giao ticp, Neu Iii nam {hi may Sl.' noi "Chao ong" neu tuoi >=90: may noi "Chilo Ric" neu tuoi >=60; may noi "Chao anh" neu tuoi >=30: may noi "ChilO ban" neu tuoi <30. Neu Iii nff thi may Sl.' noi "ChilO bit" neu tuoi >=80: rruiy nl1i "Chao Ric" nell tuoi >=50; may noi "Chao chi" nell tuoi >=25; may noi "Chao em" trong cue twang hop con lai, Chirong trinh kiem Ira cit tnrong hop ngub'i nhap go nham ki II! (kluillg pl/(ii Nam ciiug klu)llg plldi Nil).

#inc!ude "stdio.h" #include "conio.h" #include "strinq.h"

int main{) {

char GioiTinh[3]; int Tuoi:

Hoil.ai:

printW\nChao ban, ban la nam hay nu(Nam/Nu) ?\n"); scanf("%s", GioiTinh);

if( (strcm pi( GioiTinh. "Nam")! =0 )&&(strcm pit GioiTi nh, "N u")' =0» {

printf("\nHay go\" Nam\" hoac\" Nu\''''); goto HoiLai;

}

printf("\nBan nam nay bao nhieu tuoi ?\n"); scanf("%d", & Tuoi);

if( strcmpi( GioiTinh. "Nam ")==0) {

if{Tuoi>=90)

printf(,,\nC hao onq!"): else if(Tuoi>=60)

p rintf("\nCh ao bac! "); else if(Tuoi>=30) printf("\nChao an h! "): else

prin If{"\n Chao ba n '"):

}

else

{

58

if(Tuoi>=80) printf(,,\nChao ba!"): else if(Tuoi>=50) printf("\nChao bac!"): else if(Tuoi>=25) printf("\nChao ch i! "I: else

printf("\nChao em!");

} getchO; return 0;

Ket qua ch{lY chuang trinh:

Chao ban.ban la nam hay nu (Nam/Nu) ? Nu

Ban nam nay bao nhieu tuoi ? 100

Chao ba!

c) Tolin Iii switch

Toan til switch lam viec giong nhu loan llf if 016' rong cho II [Wang hop iJ tren, chi khac mot dieu la switch Iuon lam viec vci cac bieu thuc nguyen.

Cu phap ella toan til switch nhu sau: switch (Bieu thue nguyen) {

case nl:

Cac cau I~nh; break;

ease n2:

Cac cau lenh;

break: .

ease nk:

Cac cau lenh;

break; .

[default:

Cac cau I~nh;l

Trong do. IIi Iii cue Sl/lIgUyell, Mill/!, ki /1/ hoac hi/II llu/c' 'UllIg. C:k IIi phili co gi,-l. tri khac nhau. Ole cau lenh nam Jeong hai d.-iu '()' drroc goi lit than ella switch. Ta co th~ 010 [a hoat dong ella switch nhu sau:

- Tnroc lien. may se xct gi,\ If! ella Bietl thi«: nguyen, I;IY thea gi,'t tri cua bieu thirc nay rna no quyet dinh nhay toi dau,

59

- Neu gia tri nay bang ni, may se nhay toi cau lenh nam sau nhan case ni va bat dau thuc hien cac lenh tir d6 cho Mn khi gap mot toan tir break, goto, return hoac diu ket thtic '}'.

- Khi gia tri cua bieu thirc nguyen khac tit ca cac IIi, i=i +k thl su hoat dong cua switch hie nay phu thuoc vao su e6 mat hay vang mat cua default. Neu c6 mat default thl cac cau lenh narn sau default se diroc thirc hien, ngiroc lai may se thoat khoi switch va bat dau thuc hien cac Ienh nam sau dau '} . cua than switch.

Chuj:

- May se thoat khoi toan nr switch chi khi n6 gap mot toan til break hoac dau ngoac d6ng '}' chi su ket thuc ella toan til switch. Do d6 cac toan til break la khong th~ YAng mat moi khi mot nhanh nao d6 dii diroc Iva chon,

- Trang than cua lenh switch ta cung c6 th~ sil dung toan til goto d~ nhay taj mot cau lenh bA't kl ben ngoai switch.

- Khi switch narn trong than cua mot ham nao do, ta cling c6 tM sir dung mot toan nr return trong than cua switch dci thoat khoi ham d6 ixem them 2.2.2. muc 4),

Vi du 2-17. Viet chuang trlnh rna phong vice rhirc hien bon phep tinh co ban cong, trir, nhan va chia voi cac loan hang va roan nr nhap tir ban phim.

Vi du nhap 2+3 se cho ket qua la 5 ...

Gidi: trong chuang trinh can sir dung den ham fflushtstdin) dtroc khat baa [rang stdio.b d~ lam sach bo dern ban phim tnroc khi nhap ki nr.

#include "stdio.h" #include "conio.h"

int main()

{ float num 1, num2; char KyTu;

LapLai:

printf("\nHay nhap bieu thuc duoi danqv'So ToanTu So\":\n"); scanW%f%*[ \nr. &num1);

scanf("%c%f", &KyTu, &num2);

switch(KyTu)

{

case '+':

prlntt(" = %.2f", num1+num2); break;

case '-':

printf(" = %.2f~, num1-num2); break;

case "": /* ngLfai sa dunq c6 th4 g6 axb hoac aXb hoac a*b *1 case 'x':

case 'X':

printf(" = %.2f", num1 *num2); break;

case 'I': /* ngLlai sa dl,mg co th4 g6 alb noac a\b deu dltgc *1

60

case '\\':

printf(" = %.21", nu m 1/num2); break;

default:

printf("\n Toan tu khong quen biet !"); }

printf("\nBan co muon tinh tiep khong?(C/K)"); fflush(stdin):

scanf("%c" ,& KyTu);

if( KyTu=='C' II KyTu=='c') goto LapLai; getchO;

return 0;

}

Kel qua chay chuang trinh:

Hay nhap bieu thuc duoi dang "So ToanTu So": 23 + 60= 83.00

Ban co muon tinh tiep khong ?(C/K) c

Hay nhap bieu thuc duoi dang "So ToanTu So": 12 x 20= 240.00

Ban co muon tinh tiep khong ?(C/K) K

/* ******** •• ************************************************.*****************.*~*****.**** */

Van de' can gidi dap:

- Chuang trinh tren Slr dung dinh dang %*[ 'In) trong cau lenh scan! M lam gl ? hay giai thich!

- Gia Slr khong sir dung hamfflush(stdin) thl van d~ gi se xayra ? Tai sao?

3. Nhom cae I#nh dung dito' chac chu trinh

Trang lap trlnh co cau tnic, thong thirong ta can tao ra cac doan ma rna hoat dong cua no lap di lap lai thea mot quy luat nao do inhu doan rna dung cau true goto va if trong vi dlf. 2-17 cluing han). D~ thuan tien cho viec tao ra cac chu trlnh trang khi vi€t chuang trinh, Turbo C dua ra hai loai cau true I~p voi muc dich khac nhau, do la cau true I~p xac dinh (dung toe in tlt dieu khi€n for) va Call true l~p khong xac dinh (dung toan ttf dilu kllie'n while va do ... while). Cau true lap xac dinh (hay con gqi fa vong Ir;ip xac dinh) thuong hay dung cho cac thaa tac lap di l~p lai voi so'MIl ldp dd duac biet truac. Con call true lap khong xac dinh (hay con goi fa vong lfjp Hong xdc dinh) thuong hay dung trong cac tnrong hop ta chtra biet tnroc se phai lap baa nhieu Ian, so Ian lap nay thirong phu thuoc vao gia tri tai thai diem hien tai ella mot hay nhieu bieu thirc nao d6.

a) Toan tli dieu khiinfor

La toan tir dung d~ xay dung cac vong lfjp Xtlc dinh trong chirong trlnh, Trang ngon ngjt lap trlnh C, cau true ella vong lap for linh dong, hieu qua han trong Pascal, cu phap cua n6 nhu sau:

for(Bieu thirc 1; Bieu thrrc 2; Bieu thirc 3)

61

Cau_l~nh; I*than cua yang l~p*1 II oat d{JIlg CUll vong lij.p for:

B 1: T!II/C /li¢1I Biel! thuc 1 r6i dlll.W'11 sang B2. B2: Ki/II/ Ira Bi£;11 thuc 2:

- Nell Bi/II thuc 2 dung (e6 Mid rrj klu«: kllilllg) till thuc hi¢iI Gil/ 1¢1I11 h()~ic kh//i '¢II"h trong !Iuill 1'()lIg for nj'i cllilyell sang B3.

- Nell Bh'll tllif'c 2 bdllg khnilg (sai) fill chI/yell sang B-1, B3: Tlutc hi~;/I Bi/II 111/(e 3 nJi quay 1~li B2.

84: TilDe/f.

Sai (bang khOng)

(than vong l!ip)

Hi"h 2.2. So do hO",1 dQng cua loon nr for.

Vi dI:l2-18. Viet chuang trinh phat ra 20 tieng hip.

Gidi: De' c6 th~ phat ra cac tieng blp ta dung ham printf tlurc hien chirc nang cua ki tLJ Bell (ilia ASCIl ella II(J hi 7). Tuy nhien, sau khi phat ra mot tieng bip [a dn tam dirng mot khoang thai gian nhat dinh (/lell kliong fa ch! ughe tMty dj((~lIg 1l11i( m(Jt tiel/g bip dai /lUI fluJi) bang ham:

void delaytint II) diroc khai bao trong thu vien dos.h. Ham nay se thuc hien tarn dirng heat dong cua may trong khoang n miligiay.

#include "stdio.h" #inc1ude "conlo.h" #inciude "dos.h"

int mainO {

int i:

printf(,,\nChllong trlnh phat 20 liang bip"): for(i=1; i<=20; ++i)

{

62

prinlf("%c~,7); delay( 1 OOO};

} getchO: return 0:

}

Cluj Y:

- Trong than toin tufor neu muon thuc hien nhieu cau lenh thl phai d~t trong khoi lenh,

- Trang ph.in ngoac tron '0' cua roan nr for dtroc chia thanl; :3 phan phan

each nhau boi dau ";'. Cac dau ';' nay I~ bat buoc phai co mat, kc ell tnrong hop mot hoac mot so Bh-;i, itu« bi vang mat. Trang moi phan lai co lh~ dat nhieu han mot bieu thirc pharr ciich nhau boi ddu plui'y ".' de thuc hien de cong viec khac nhau thea Ih(r nr xac dinh tu trai qua phai, Khi phan clura Bieu thuc 2 co nhieu han mot Bi~u tlurc thl tinh (!lillg sai ella loan loan tir/or sc I~\ tinh dung sai cua bieu there cuoi cung trong day bieu thirc ella phan nay. Ta e6 Ihe hieu ki han hoar dong ella vongfor thong qua vi du 2-19 dtroi day.

- Toan nr fur cung co the sir dung d~ xay dimg de vong l,)p khong xac dinh bing each dieu khien hop li cac bieu thirc ella no.

l'i du 2-19. Hay sir dung roan ur for M xay dung vong lap khong xac dinh thay cho vai tro ella roan nr goto va roan nr iftrang vi du 2-17 iJ tren.

#include "stdio.h" #include "conio.h"

lnt maii1() {

float num 1, num2; char KyTu='C';

for( ; KyTu=='c'!IKyTu=='C'; printf("\nSan co muon tinh tiep khong?(C/K)"), scanf("%*[ \n1%c", &KyTu»

{ .

printtr\nHay nhap bieu thuc duoi dang \~So ToanTu 50\";\n"): scanf("%f%"[ \n]". &num1):

scanf("%c%f, &KyTu, &num2);

switch(KyTu)

{

case '+':

printf(" = %.2f',num1+num2): break;

case '.':

printf(~ = %.2f' ,num 1-num2); break;

case '":

case 'x':

case 'X':

63

printf(" = %. 2f' ,nu m l·n um2); break;

case '/':

case '\\':

printf(~ = %.2f',num1/num2); break;

default

printW\n Toan tu khong quen biet l"):

}

} getch(): return 0;

}

Klt qud cht;ly chuang trinh cimg eho ket qua tuang tu:

Hay nhap bieu thuc duoi dang "So ToanTu So": 23 + 60= 83.00

Ban co muon tinh tiep khong ?(C/K) c

Hay nhap bieu thuc duoi dang "So ToanTu So": 12 x 20= 240.00

Ban co muon tinh tiep khong ?(C/K) K

- Bilu thue 1 bao gio cling diroc thirc hien dung mot Ian.

- Khi Bilu thire 2 vang rna: thl n6 luon duoc xern la dung. De ra khoi chu

trinh trong tnrong hop nay ta phai dung den cac lenh break, goto hoac return ben trong than vong lap,

- Than cua vong for c6 th~ la mot cau lenh hoac mot khoi lenh.

- Ben trong than cua vong for lai c6 the chira cac toan nr for khac. Di~u do

c6 nghia III cac toan tirfor c6 tbe d~t 16ng nhau.

Vi du 2-20. Viet chuang trlnh in ra man hmh ban CO qu6c te (ki II! d6 haa).

1* ****.***~************* •• ********.***********~.****.********.****.******** ••• ********~***. */

#include "stdlo.h" #include "conlo.h"

/* *******.**************.****~*.**~***********************************************.***.**** *'

int mainO (

int i, j;

for( i= 1; i<=8; i++) (

for(j= 1; j<=8; j++)

if«i+j)%2==O)J*Xet cac 0 cling mau*/ printf("\xDB");I*TO hinh vuOng tr~ng*1 else

printfr "): I*£>a tr6ng->cac 0 den (Ia'y theo rnau nen)·;

64

printW\n");/*Xet dong tiep theo*'

} getchO; return 0;

b) Toan tiI die"u khiin while

U. toan tir dung d~ xay dung cac vong lap kh6ng xac dinh kie'm Ira dieu ki¢Jl truoc. Cu phap cua n6 nhu sau:

while(Bieu thirc)

C&u_l$nh; I*Than yang I~p while'"

II o~1 dl)ng c ria toan Iii while:

Bl : KJuJi lao, chudn bi ban Jail. 82: Kii'm ira Bitu Ilu(~:

- Nlu eu« thue dung (c6 gia tri kJuic khong) lhi Chl'.V/1l sang B3.

- Nett Bilu thuc bang kliong (sai] thi c/wytll sang B4.

B3: Thuc hifll cau '¢lIh hoiic kho'i /¢nh troug I/U111 vong li;ip roi quay lai B2. B4: Tlloat.

Sai (oo.ng khong)

ThJ!C hien Cdu_l~nh

(than vong lap)

Hlnh 2.4. So d6 hoat dong cua toan tll' while.

Chily:

- Trang than vong l~p while ttai vi tri eua Cdu_l¢nh) neu mu6n thirc hien nhieu cau lenh thl phai dat trong mot kh6i lenh.

- Than vong lap co th~ duoc tlurc hien mot hoac nhieu W.n va cung co th~ khong duoc thirc hien IAn nao neu ngay tir ban dau Bilu thuc da sai (bang khong).

- Cung gi6ng nh 11 toan tir Jor, trang ca p ngoac tron '()' sau tir khoa while ta co th~ dat nhieu, hen mot bieu {hue phan each nhau bM dau phay ','. Tuy nhien tfnh dung sai cua day bieu thirc se la tinh dung sai cua bieu thirc sau cling trang day.

- Ben trang than cua mot toan tir while lai co th~ la toan tir Jor hoac while khac, N6i each khac la ta co th~ xay dung diroc cac chu trlnh long nhau.

Q5·GTMNLTC

65

- PMn khoi tao la filt quan trong nharn tao ra gUi. tri ban da.u eho Bilu thue tnroc khi vao vong I~p while.

- Neu Bi~u thirc trong '()' ciia vong l~p while IUCIn dung, ta se eo mot vong lap vo tan, Do do trong khi viet vong lap, bao gio ta cling phai kiern tra tinh dirng cua vong lap do. Sau day la mot vi du vi pham tinh dirng cua vong l~p do si'r dung bien dieu khien mot each bira bai,

Vi du 2-21. Vi du sai vi si'r dung bira bai bien dieu khien,

,. ***.***~***~~ •• *****~******.******~~*************~***** •• ***~**~~~**************~**.***~* ~I

#inelude "stdio.h" #include "conio.h"

int mainO {

tnt i=10; while(i!=O) (

printf{"\nGia tr] cua j la: %dH, i); for(i= 1: i<2; j++)

printf(" %c", 7);

--i;

} geteh{); return 0;

}

/* ********~~~*********~~~*~**.******~~* •• ******************.******* •• ***.**~**~**~~.**.**** */

Vi du 2-22. Viet chuong trinh eho dong chtr Hello 1 chay ngang man hinh trang che do van ban cho den khi bam phim Enter.

Gidi: De co the giai quyet diroc van de nay ta can dung them ham kiem tra b¢ dem ban phim int kbhitivoid), ham nhan mot ki til tir bo dem ban phim int geteh(void), ham xoa man hinh clrscri) va ham di chuyen can tro man hlnh den mot toa d¢ (x,y) bat kl (rang che dQ van ban gotoxy(x,y). Cac bam nay deu duoc khai baa trang thu vien conio.h. Ham kbhit se eho gia tr] khac khong neu c6 phim da duoc bam (b¢ dem ban phim kluic r6l1g) nguoc lai cho gia tri bang khong.

/* .*** •• *******~.**** •• **.******************************~***** ••• ** ••• **********~********** */

#include "stdio.h" #include "canio.h"

/* **************~************~********* •• ** •• ***~***~****************** ••• ********* •• ****** */

int mairu) {

int i= 0;

1* Lam cho bi? d~m trd nen rbng tnrcc khi bt.t dau chay ehO' */ wh i le(kbh itO)

geteh():

1* Dong chir se chay cho den khi bam phlrn Enter */ while(1)

{

clrscrr);

66

1* Neu dong chrt chay den cuoi man hlnh thi quay tro lal *1 if (i==BO)

i=O;

gotoxy( i++, 10);1* Lam cho dong chCt chay ngang*1 printf("%s", "HELLO !");

delay( 10000);

1* Kiem tra xem phim Enter co b] bam ? "I if (kbhit())

if(getchO=='\r')

break;1* £lung, thoat?

}

return 0;

}

,. *****.***************~~~*~*******.************~~***~*~***~*.*** •• *****.******~~~******.~* */

c) Toan tii die'u khiln do ... while

Trong cac roan tis for va while da: xet i'J tren, viec kiern Ira dieu kien ket thuc diroc lien hanh i'J dau cua vong lap va do d6 than vong lap co th~ se kh6ng drroc thirc hien lfin nao neu bilu thuc dieu kien ngay tu ban dau da khong dUQ'C thoa man. Khac voi hai roan tir nay, roan tir do ... while lai kiem Ira dieu kien ket thuc i'J cuoi vong lap, cho nen than cua yang lap nay bao gio cling diroc thirc hien it nhat mQI Ian tgiong vong hlp repeat until trong Pascal, my nhien do ... while se lap trong khi dieu kien con dung, ngiroc lai repeat unlill<:Li lap cho den khi dieu kien dung). Can ye each thirc lam viec thi do ... while lam viec luang nr nhu vong lap while. Cu phap cua toan tiI nay nhu sau:

do

Cau_l~nh;l*Than cua vonq l~p*1 while(Bieu truro);

H oat dong c ua toan tu do while:

Bl : TlII!C hien diu I¢IIII hodc kJufi i¢1I1! trong than vong lap. B2: Kiem tra Bii'u {hue:

- Nell Bilu thuc dung (co gia tri kJu1c khong] thi quay lai B1.

- Nell eu« thuc bang khong (sai) thi ehllyill sang B3.

B3: TJlOat.

(than vong I~p)

Dung (khac khong)

Hinh 2.5. Sa do hoat dong cua loon Itr do ... while.

67

Chuj:

- Cac luu y cua roan ttt while ciing dung cho toan tir do ... while.

Vi df:l2-23. Viet chuang trinh tinh call bdc hai cua mot s6 duong a thong qua cong there truy hoi sau:

X n+1 = 1-( X n +: ); voi n >=0, X 0 = a; Qua trtnh lap ket thuc khi thea

n

man he thtrc l(x n+1 - X n)/ X n I s t • voi e nhap tir ban phirn. Khi do gia tri cua .\;,+1 diroc xem 1a gia tri gan dung cua can hac hai cua a (voi sai st/ e ). Trong chuang trlnh ta can dung ham double Jabs(double) M tnt ve gia tri tuyet d6i cua mot s6 thtrc, ham nay khai bao trong math.h.

/* ***~*~*********.****.***.~*~~****~***~~******.****.******~*****~~***********************. */

#include "stdio.h" #include "eonio.h" #inelude "rnath.h"

int main() {

double a, Epsilon, CanBacHai, Xcu, Xmoi; do

{

clrscrt):

printf("\nHay nhap so duong a va so duong EpSilon vn"): scanf("%lf%lf", &a, &Epsilon);

}

while((a<O)II(Epsilon<O»; rehl nhap cac s6 dLlcmg"/ Xmoi= a: 1* £lieu kien crau*/

do

{

Xcu=Xmoi; Xmoi=(Xcu+ aIXcu)/2;

}

whHe(fabs( (Xmoi-Xcu )/Xcu» Epsilon):

printf("\nCan bac hai cua % 1 0.2f la % 1 0.4f", a, Xmoi); getchO:

return 0;

}

/* ******** •• *** •• *********~***************************.**** ••• ***************************** */

4. Nhom cdc l~nh die'u khiln khac a) T oan tli break

La mot toan til dieu khien dac biet cho phep ra khoi vong lap for, while. do while va toan tir switch trong tnrong hop can thiet khi dang thirc bien cac cau lenh trong than vong l~p hoac than cua switch. Dieu do co nghia la roan tir break cho ta kha nang ra khoi mot vong l~p hoac switch (fle mot dilm bat ki bin trong than vallg l£jp hodc than switch) rna khong dung den dieu kien ket thuc vong lap hoac khong mu6n cac lenh sau break trong than switch diroc thuc hien tiep,

68

ChIlY:

- Khi c6 nhieu vong lap hoac switch long nhau thl cau lenh break chi thoat ra khoi vong lap sau nhat itrong cung) c6 chua toan tir break d6 rna thoi,

- M9i toan tiI break deu c6 th~ thay bang toan tiI goto voi nhan thich hop,

- break thuong diroc sir dung khi vong lap for c6 th~ thirc hien s6 IAn lap it

han s6 Mn lap dii diroc xac dinh tnroc, trong than cua switch va trong cac tnrong hop ta phai kiem tra dieu kien k€t thuc cua vong lap while ben trong than ella n6 nhu trong vi du 2-22 dii duoc trinh bay i:J tren, .

Vi dlJ- 2-24. Viet chuang trlnh xet xem mot s6 nguyen dirong II (wh n IlluJp tit ban phimt c6 phai I;), mot s6 nguyen t6 hay khong ?

#include "stdio.h" #incl ude'conio. h" #include "math.h"

int mainO {

char ch:

int i, Dung, n;

r Thirc hien chuang trinh cho den khi bam 'K' hoac 'k"? do

{

Dung=O; 1* gia sa 56 dola hop 56"/ 1* Chi nnap 56 nguyen duang »]

do

(

printf("\nHay nhap so nguyen duong n = "); scanf("%d~, &n):

if(n<O)

(

printf("%c", 7); printf("\nHay nhap lai"):

}

} while(n<O);

t" Xet tfnh nguyen t6 cua 56 vira nhap */ for(i=2; i<= sqrt(n); i++)

if( (n%i)==O)

break; 1* Thoat luon "t

if (i>sqrt(n) && (n!=1) && (n!=C)) r da xet het cac uoc 56 co the co" Dung=1: t: Chac chan la ~6 nguyen to "/

if(Oung)

printf("\nSo %d la mot so n~luyen to",n); else

printf("\nSo %d la hop 50",n); getchO;

}

69

while( clrscr(}, printf("\nBan co tiep tuc nua khong (C/K) T), scanf("%*[ \n]%c", &ch), ch!= 'K' && ch != 'k'):

return 0;

b) ca« l~nh continue

Trai voi roan til break (dung de'tllOat ra khoi vong lqp) cau Ienh continue dung d~ bat dau mot vong lap moi ella ehu trinh sau nhat chua toan ti't do. Noi mot each khac:

- Khi gap roan ti't continue ben trong than ella mot toan til for, may se bo qua cac cau lenh can lai trong than/or (salt continue) chuyen sang thirc hien Bilu thuc 3 d~ khoi d.iu eho Yang lap moi tiep thea:

- Khi gap toan til continue hen trong than ella yang lap while hoac do while, may se bo qua cac Ienh con lai trong than yang lap (sail continue) chuyen toi Kiim tra Bie'u thuc sau til" kh6a while d~ khoi dong eho yang lap tiep thea (llill Hi/II tlurc con dill/g) hoac thoat khoi Yang lap (II/II Bie'u tlu«: saii.

cn« f:

Toan ur continue chi ap dung cho Cat vong lap rna thoi (kli(!llg (IP dung clio toau flf switch).

Vi du 2~2S. Viet chuong trlnh nhap cac ki til tir ban phun sau d6 chi cho hien len man hinh cac kf t~r HI. chi] hoa. Chtrong trlnh ket thuc khi bam phim ESC (lilii ASClf nia /10 bdng 27).

au: D~ kiern tra xern mot kf tu nhan duoc co phai la chir hoa hay khong ta dung ham int isupperiint KyTu) duoc khai 00.0 trong thu vien ctype.h cua Turbo C. Ham se cho mot gia tri khac khong (dung) neu KyTu 1<\ mot chi! hoa, ngiroc 1,.1i cho gia tri bang khong, M9t diem can luu y niia la cr day ta khong th~ dung ham scan/ d~ nhap phfm diroc (vi ham scan! se clio luen tat cd cac ki II_( vua IIlujp ra man hillh) rna ta sir dung ham getch duoc khai 00.0 trong conio.h.

#include "stdio.h" #include "conio.h" #include "ctype.h"

int mainO (

char KyTu; whiJe(1 )

{

KyTu=getchO; I·Nh~p kf tu */ if(!isupper(KyTu» I*L3: kf nr khac chlt hoa */ if(KyTu==27) 1* '8ieu k'ii;ln thoar" break;

else r ChL1a thoat, tiep tuc yang sau? continue;

70

1* La chir hoa, dude hien thi ra man hinh?

printW%c~, KyTu); .

}

return 0;

c) Cau lenh return

La. toan nr dieu khien dac biet dung M thoat ra khoi mot ham va tra ve cho ham mot gia tri xac dinh nao d6 nam trong bieu thirc sau tit kh6a return (trollg chuang 4 se tim hilt! sdu han ve' ham trong IIg611 ngif ldp trinh C). Cu phap cua no nhu sau: return [Bilu thu»];

Chili:

- Bi~u thuc sau return c6 th~ vang mat inong truong hop ta kliong cdn (I'd w; gia tr] cho m91 ham).

- Khi gap return may se thoat ra khoi bat kl mot vong lap nao (ke' cd truoug hap co "hieu vong It;ip long nhau) va thoat luon ra khoi ham e6 chua cac yang lap d6.

- Khi g~p mot toan ti'r return e6 chua Biiu thuc, thl gia tri cua bieu thirc se dircc chuyen kieu cho phu h9P voi kitiu tea ve cua bam truce khi n6 duoc gan cho ham.

5. Mtjt srI vi df!. minh hoa

Vi df! 2·26. Vi€t chuang trinh nhap vao mot so nguyen N co gia trj tir 0 den 9999. Hay in ra bang chtr gia tri cua sO' do (".j du: 106 ill ra /0 m91 tram linh Salt).

#include"stdio.h" #include"conio.h" #define MAX 4

mainO {

int SoNguyen, i, k, j, ChuSo[MAX]; 1* chua cac chCt sO' cua sO' S8 nh~p*1 printf(''\nHay nhap mot so nguyen tu 0 den 9999\n");

scanf("%d", &SoNguyen);

ChuSo[O]= SoNguyen;

for(i=MAX-1 ; 1>0 ; --i)

{

ChuSo[i]=ChuSo[O] % 10; ChuSo[O]1= 10;

}

k = -1; /* dieu chin h de k ch r VaG ph a n tlt dau tien khac kh6ng trong ma ng* / r-t: /* dieu chin h de j chi vao p han tLt eu6i ell ng khac khOng trong mang */ for(i=O; i<MAX; ++i)

if( Ch u Soli]! =0) break; if(i<MAX) k=i: for(i=MAX-1; i>=O; --i) if( Chu So[i]! =0)

71

72

break; ;f(i>=O) j= i;

fort ;=0; j< MAX; ++i) {

if(k== -1) {

printf(" Khong"); break;

} switch(ChuSo[ij) {

case 0:

if ( (i>= k) &&(i<=j) ) /* la s60 co nghi"a "f {

;f(j==2) r la hang chuc? {

if(ChuSo[3j!=O) 1* hang dan vi khac kMng*1 printf(" linh "):

}

else if(i==3) r Iii hang dan v)*/ {

if{ChuSo{2J!=1) f* neu khac s6 rnuoi? prjntf(~ muoi ");

}

else printf(" khong ");

}

break; case 1:

if 0==2) r Mng chl,lc*/ printf(" rnuoi "): else printfr mot "): break;

case 2:

printf(" hai"): break;

case 3:

printfC ba "); break;

case 4:

printf(" bon "): break:

case 5:

printf(" nam "): break;

case G:

pI intW sau "): break;

case T:

printf(" bay"); break;

case 8:

printf(" tam ~); break;

case 9;

printf(" chin "): break;

} switch(i) {

case 0;

if(i>=k) 1* chi hi~n cho nhCtng 56 co nghTa */ printW nghin "):

break;

case 1:

if((i>=k)&&(i<=j)) r chi hien cho nhCtng so c6 nghTa */ printf(" tram ");

break;

case 2:

if{i>=k) if{(ChuSo[3]!=0)&&{ChuSoI2J!=0)&&(ChuSa[2J!= 1 )) printf{" rnuoi");

}

} getchO;

Vi du 2-27. Viet chirong trinh tfnh va in ra tong thea cong thirc sau:

S = 2004 + 1 + ~! + ~! + ... + ~! voi n la mot s6 nguyen duang bat kl,

Gidi: NMn xet rang tong tren diroc phan fa lam hai phan, mot phan khong eo quy luat tta xem 1I111( gia trj ball ddu Clia tbllg, do la 2004) va mot phan eo quy Iuat. Phan eo quy luat co th~ diroc tinh bang each tfnh rieng tirng phan li'r cua tcing roi Ian hrot cong cac phan nr do vao tong chung.

#include "stdio.h" #include "conio.h"

int mainO {

int l, n:

double Tong. PhanTu_i;

Tong=2004; /* gia tr! ban dau cua tong *1 PhanTu i=l;

r Chi nh$p 56 nguyen dLfong n kl do

{

printf("\nHay nhap so nguyen duong n= "); seanf("%d", &n);

if(n<=O)

73

printW\nMoi ban nhap Ian;

} while(n<=O);

r Tfnh t6ng da cho " forti:::: 1; i<::::n; i++)

{

PhanTu_i I::::i;

Tong +:::: PhanTu_i;

}

printf("\nTong eua chuoi da eho voi n= %d la: % 1 0.2f ", n, Tong): geteh();

return 0;

Vi du 2-28. Viet chuang trinh xep cac dau '*' thanh tam giac can II dong, vci II doc tu ban phim.

1* .***.*********~~*~~*.******** ••• **.*******~***~~.~*~~****.********~~.*~******.**** •••• *** */

#include "stdio.b" #include "conlo.h"

int maim) {

int n, i, j; clrscrt):

printf("\nCho biet so dong\n"); seanf("%d", &n);

clrscrt):

for(i=1; i<=n; i++) (

gotoxy{40-i, i);

for(j= 1; j<=2"i-1; j++)

{

} printf("\n") ;

}

gotoxy(10, 24);

printf("An mot phim bat ky de ket thue l"); getchO;

return 0;

}

Vi du 2-29. Viet chuang trinh tinh va dua ra man hinh c.ic c~p gi.:i tri x,j(x) cua ham s6 ({x) = ~x5 + M voi x lay day gia tri -1; -0.9; -0.8;, .. ; 4.9: 5.

#include "stdio.h" #include "conio.h" #include "rnath.h"

int main{)

74

{

int Oem; float x, f; clrscrt):

printf("% 1 Os% 1 Os\n", "x", ~y=f(xn; x=v l.:

Dem=O; while(x<5) (

if(x==O) I=O: else

f=pow( (pow(x, 5)+pow(fabs(x) ,0.5)),0.2); printf("%10.1f%10.4f\n", x, f);

Dem++;

x+=0.1 ;

if(Dem%23==0) 1* neu hien qua 23 dong thi dung l~i*1 {

printf("Go Enter de xem tiepin"): getch();

} qetcht): return 0;

Vi du 2-30. Viet chuang trlnh mo phong /I lAn sinh va tfnh xem co may hln sinh can trai.

Gidi: Viec du doan sinh can trai hay can gai duoc tfnh mot each ngau nhien, neu s6 phat fa nho hem nl2 chang han (/I Iii mot so" cho truac'; thl diroc coi la sinh con trai, nguoc lai la sinh can gai, Chirong trtnh si't dung ham phat s6 ngau nhien int randomiint n) cho mQI s6 ngau nhien til () den /1-1 va ham void randomizeivoid) de khoi diu IX? s6 ngau nhien bang mQI gia rri ngau nhien, Cac ham nay duoc khai baa trong stdlib.h.

#include "stdio.h" #include "conlo.h" #include "stdlib.h"

int mainO {

int i,n, OemTrai; clrscrt):

printf("\nCan rna phong bao nhieu Ian sinh? \n"); scanf("%d", &0);

DemTrai=O;

randomize{);

for( i= 1; i-c=n: i++) {

if( random (n )«lnt)(n/2))

75

OemTrai++;

}

printW\nSo Ian sinh can trai trong %d Ian sinh la: %dH, n, DemTrai); getch();

return 0;

}

2.3. cAu HOI vA sAl T~P

1. Hay so sanh bi~u rhirc trong ngon ngfr C voi bieu thirc trong toan hQC.

2. Bi~u thirc quan he va logic trong ngon ngfr 11).p trlnh C va ngon ngff 11).p trlnh Pascal khac nhau a diem nao?

3. Viec chuyen d6i ki~u gia tri xay ra khi nao? nguyen tac hoat dong ra sao?

Cho vi du minh hoa.

4. Phan bier cac phep thao hie Bit &. I voi cac phep logic && va II. Cho vi du minh hoa.

5. Phan biet cac cau lenh ++i, --i voi i++, i--. Cho vi du minh hoa.

6. Phan biet vong lap xac dinh va vong li;lp khong xac dinh? Cach su dung lung loai. PMn bier roan nr switCh voi toan tir ifrna rong cho 1/ hra chon, co thi viet lai VI du 2-16 sang cau true dung Ienh switch hay khong? tai sao?

7 (>1. Ta co the chuyen dbi cau tnic ri nhanh if. switch va cau true lap for, do ... while thanh cau true while diroc khong? tai sao?

8. Hay trlnh bay vai tro cua cac toan tu break, continue.

9*. Tai sao khi viet chuang trinh bang Macro, kich thtroc cua chuang trlnh Iai IOn han nhung nhln chung chay nhanh hen la viet chuang trlnh bang ham?

10* . Hay viet lai VI d u 2-11 rna kh6ng sir dung ham pow().

Gat j: ta co tM tinh/=y' nhu sau:

Tnrong hop y>O ta co: /=exp(x*log(y)

Truong hop y<O ta co the dua ve truong hop ye-O, duang nhien each viet con phu th uoc vao gia tri c ua x, chang han khi X= II (21/ + 1) thl: /=-exp{:r*fog( abs(y))).

Trang d6 double exptdouble x) se cho gia tri e' va double logtdouble x) se cho gi<i tri lnix), Ca hai ham nay deu di"i duoc khai baa trong thu vien math.b ella Turbo C.

11. Hay viet lai VI du 2-12 c6 kiern tra dieu kien hinh thanh tam giac.

12. Lap chuang trinh giai phuong trlnh hac hai. Dira ket qua ra man hinh,

13. Nhap ba s6 a, b, c tinh va in kct qua bieu thtrc sau day ra man hlnh (co bien luan cac truong hop vo nghia):

ab + 4a - 6 (1- a)(tg(b - 2) + 3)

--------+~~~--~~

3b - sin{bc) cos a + sin b

• La de bui kho dn xuy nghi nhicu.

76

14. NMp toa dq hai diem tu ban phim. Tinh va in khoang each giua hai diem d6 ra man hinh.

15.' Nhap toa do mot diem nr ban phim. Xet xem diem d6 c6 thuoc dirong phan giac cua g6c phan ur thtr nhat hay kh6ng?

16. NMp ba bien 56 nguyen nr ban phim. Hay xet xem ba s6 d6 c6 tao thanh

cap s6 nhan hay khong?

17. Xac dinh 56 Ian lap cua chu trinh trong chuang trlnh sau day: #include "stdio.h"

#include "conio.h"

int mainO

(

int a=1, b: float x=O: b=a; whiletallb) (

x=2~x+1; if(x>O)

(

a=O; if{x<200) b=O;

} printW\nx=%f',x);

} getch();

}

18. Nhap II 56 tir ban phim. Tfnh va in ra man hinh gia tri cua s6 160 nhat trong " 56 do,

19. Nhap ba 56 a, b, c tu ban phim. Hay tmh va dira ket qua ra man hinh gia tri 160 nhat trang cac bieu (hue sau: l-Zsina, cos'b va ab-sinacosb.

20. Nhap gia tri cua x tu ban phim. Tinh va in gia tri bieu thirc sau day ra man hinh:

{2X+3

f(x)= cos{2x + 1) + x neu - 5 <= x < 10

4x+7 neu x >=1Q"

21. Cho b6n s6 nguyen a, b, c, d. Dat SI= a+b+c+d, S2= ab-ed. Hay kiern tra xem Sl e6 chia het cho S2 hay kh6ng? Neu chia het thi in fa thirong 56, ngiroc lai in fa 56 duo

neu x <-5

77

22. Up chuang trlnh giai bar phuong trlnh a~+bx+e<O voi a, b, e HI. cac h¢

so nhap til ban phim.

23*. Tinh va in t6ng thea c6ng thirc sau:

S = 2004 + 1- ~! + ~! - ;! .,. + (1)(n-1) ~! voi /I la mot so nguyen dtrong bat kl. 24*. Tfnh va in tong thea cong thtrc sau:

2 3 n

S x x x,. \' "h h ir bs hl

=l+x+-+-+ ... +-valX a rnot so t trc n upar anp tm.

2 3 n .,.

25 *. Lap chuang trlnh tinh gia tri cua e' theo cong thirc xap Xl sau:

2 n

'1 x x x,. d hi h xa h" b' hi

e = + -11 + -21 + ... + -I val (> c in xac f n <;l.P tu an p im.

.. n.

26. Lap chuang trlnh d9C vao hai s6 a, b roi tinh y=J5x~+x+72, trong d6: x=a+b neu a<b

x=15, 172 neu a=b

x=a-b neu a>b

27. Lap chuang trinh d9C x tir ban phim roi tmh: Y = ~ + +1 z +

, {2Sin2(6,14 + x) neu x > 0

trong do z = .JX sin x

neu x <= 0 e-x + x

28*. Nhap van mot s6 thuc tir 0,01 den 99,99. Hay in ra man hinh each d9C s6 d6 thea tieng Viet, Vi d1,l12,22 thi in ra "Muoi hai phay hai muoi hai".

29. Viet chuang trinh d:'o cac s6 trong mot s6 nguyen cho tnroc. Vi du nhap vao s6 12345 thl phai in ra 543:': 1.

30. Viet chuang trlnh xep ,~ac dau * thanh mot hinh thai II dong, voi n doc nr ban phim.

31 *. Viet chuang trinh phan tich so nguyen II (11 Il/lljp tit ban phim) thanh thira s6 nguyen t6.

32. Lap chuang trinh cho phep nhap tir ban phim cac ki tu, chuang trinh se thoat khi bam phim ESC. Hay dem xem da go bao nhieu phim la chu hoa, bao nhieu phirn Ia chir thuong, Dua ket qua ra man hinh khi ker thuc nhap,

33. Lap chuang trmh rno phong viec gieo cung mot luc 2 xuc xac /I Ian va dern s6 Ian xuat hien (bng s6 diem bang 6.

34 *. Viet Iai vi du 2-15 de' co th~ tro thanh mot chuang trinh tu van tinh cam

cho moi nguoi. Noi dung tu van tuy thich. .

78

Ch u an g 3

T6 cnnc CHUONG TRINH vt M!T DcrLI~U

M1,lC TIEU CVA CHUONG NAy

>- nu« mOl tuang quail giiia cdu true dii lieu va gidi tluuit,

>- Hie'u each 1/0(;11 {h)J1g ding nhu each 1t(1I trii etta cdc loai cdu true dii lieu tliuang g¢ip trong bo nlur.

>- SIt dung thanl: thao cac cdu true dif Ii¢/! ciing 1111/( gidi thudt C{/ ban.

3.1. CAU TRUe DU L1~U, GIAI THU~T vA cAc VAN DE LIEN QUAN 3.1.1. Thuat toan va ghii thuat

1. Thuat loan

Khai niern thuat toan (algorithm) b&t ngu6n tir ten mot nha toan hoc nguoi Trung A Ia Abu Abd - Allah ibn Musa al'Khwarizmi. tlurong goi Ia Al 'Khwariuni. Trang mot cuon siich viet ve s6 hoc Ong da dung phirong phap mo ta rat r5 rang, mach lac each giai cua mot s6 bai toano Ve sau, phirong phap rno d each giai roan cua Ong dircc xem Iii chuan mire va diroc nhieu nha toan h9C tuan theo. Khat niern Algorithm ra doi dua theo each phien am ten cua Ong.

Djnh nghia:

TIIII(it toan Iii m¢l day cae buac clujl che- va r5 rang, xac dinh m¢t triuh fI/ cac tltao tac tren mot s6- dOl tuang nao d6 sao clio sau m¢1 S(J 1!l1~1 han ldn thuc hi¢n fa tim duoc kef qua nhu 1I10llg doi.

Viec nghien cuu ve thuat toan co mot vai tro rat 160 trong khoa hoc may tfnh, moi van de, bai toan muon duoc thuc hien tren may tfnh dien tir deu phai co mot 111119-( totui hoac gid; thudt xac dinh cho no, dong thoi ket qua thuc hien nay cling phu thuoc rat nhieu VaG rlltl9-t toan hay gid; thwjt da duoc sir dung, Trong khoa h9C may tfnh, moi thuat loan tlurong dUQ'C the hien hoi mot thu tuc gam mot so hiru han cac cau Ienh rna theo do ta se dat den loi giai cho bai toan dang xet.

2. Gidi thudt

Trang khi tlrn kiern lbi giai cho cac bai roan thuc te, cac nha khoa h9C nhan thay rang:

~ Co nhieu bai roan cho den nay van chua xac dinh diroc lieu co ton tai mot thuat toan d6 giai quyet hay khong ?

~ Co nhieu bai toan da: co thuat roan d~ giai, nhung khong chap nhan duoc do thoi gian d~ giai bai toan thea thuat toan do qua 16n hoac cac dieu kien cho thuat toan kh6 dap tmg.

79

- C6 nhtmg bai toan c6 tbe giai ducc mot each hiru hieu bang mot loi giai nao d6, nhung loi giai nay lai vi pham mot s6 tinh chat cua thuat toan,

Trang thuc tien, c6 rA't nhieu tnrong hop nguoi ta chap nhan cac each giai [huang cho ket qua t6t (tat nhien Iii kliong phdi /tIC "fLO ciing tot) nhirng it phuc tap, hieu qua va kha thi, D~ c6 th~ du bao thai tiet mot each chinh xac cho ngay hom sau, thong thirong nguoi ta phai giai mot bai toan t6i uu voi khoang J.'5 rin s6, thea tfnh roan elm cac nha khoa hoc (hi thoi gian de thirc hien cong viec nay thea dung thudt toan phai mat nhieu nam, nhu vay ket qua thu diroc se khong con c6 gia tri gl nira. Trang thuc te, ngiroi ta c6 nhirng each giai khac dan gian han rat nhieu va cho ket qua ciing wong d6i kha quan, dirong nhicn ket qua doi khi co the khong dung vi n6 vi pham tfnh chat che cua thuat toan. Do do nguai [a dii nghi den viec rna rong khai niem thuat roan, lam cho thuat toan bot "cung IIJJ(jc" han, kh6ng doi hoi qua chat che vii 1'5 rang rna van cho ket qua chap nhan t/U'1C. Chap nhan diroc a day c6 the hieu nhu mot ket qua grin dung, mot ker qua grin sat voi thuc te nlnrng kha (hi, hoac mot kef qua dii bi rang buoc trong mQI s6 dieu kien nhat dinh nao d6 ... Nhirng each gidi chap IIh4n duoc nhung khong hoan toan dap irng driy du cac tinh chat cua mQr thuat roan nhu the goi la gidi thuat,

Giai thuat d¢ quy (xem chuang 4), giai thuat J/g/iu IIhiell, cac giai thuat Heuristic:., chfnh Iii SI! rna rong cua khai niem IJII/(;i! (0(111. D~ thuan tien trang vice SLr dung ngon til, trong giao trlnh nay chung toi sc dung khai nicrn gidi (1IIU)f de chi chung cho thudt toan va gidi thuat,

3.1.2. Call true du li~u va cac van de lien quan

Cau true dfr lieu va giai thuat Iii hai thanh t6 co m6i quan h¢ gun bo chat che voi nhau (rang mot chuang trlnh may tinh, Viec tim kiern mot cau true dfT lieu va cung voi no la cac cau true dieu khien de viet mQL chuang trinh giii.i mot bai roan nao d6 phu thuoc nlt nhieu VaG gidi tliudt de giai bai toan d6. Nguoc lai moi gii'li thuat dua ra cling phai quan tam den viec no SC Xl! If tren cac doi nrong diJ lieu nao? (trollg 111(;( sf;' vi dl,l /(lig dung .w! pluin ticlt ki han /Ju;;' qUail h~' lid)'). Ta co the trich dan mot cau n6i neii tieng cira I ', Wirt" nhu sau:

C/U((!lIg trinh = Gidi tllll{if + Cdll true drr Ii¢" (Program = Algorithm + Dnta-structure)

Thong thirong, mci mot ng6n ngli I~p trinh bao gia cling cung clip san cac cau tnic dir lieu tien dinh (ki211 Sif nguyen, so" (IWe, ki I{( ... ) cho ngiroi lap trlnh, tuy nhien cac cau true nay Ja khac nhau voi cac ng6n ngli lap trinh khac nhau, Nlurng trong hau het cac tnrong hop ta deu phai tu xay dung len cac cau true dli lieu rieng dua tren cac kieu diJ lieu eta co M c6 the dap (rug diroc cac yeu cau dat fa. Moi cau true diJ lieu nay deu co nguyen tilc hoat dong, cac phep tac dong va each thuc luu tnt rieng. Do d6 khi nghien ciru bat kl mot cau true diJ lieu nao ta deu phai nghien ciru tren cit ba phuong dien d6.

12. eAe CAU TRUC nULI¢U CO BAN 3.2.1. Con tro

1, COil tro, killl con tro, kiiu diu chi

Con IH; la mot bien dac bier dung M chua dia chi cua bieJ/ va luun. VI co rat nhieu loai bieJ/ va helm khac nhau cho nen cling c6 nhieu loai con tro khiic nhau, V[

80

du COil Ira kie'll int dung de clnra dia chi cdc bien kie'u int, COil Ira killl float dung de chua dia chi cdc bil/! kiiu float ... Ta n6i rang, mbi killl COil Ira se duoc gan nrong irng voi mot killl dia chi nhat dinh. Cach Hun viec cua cac can tro irng voi cac kieu dia chi cGng rat khac nhau (xem vi du 3-2). Viec gan cac can tro voi cac kieu dia chi khac kieu se dan toi viec nhan duoc cac canh baa khong mong mu6n vs c6 the gay ra ket qua sai, loi bien dich, tharn chi treo may. Do do khi sir dung can tro ta can het sire than trong, mac dau vay, viec su dung can tro la mot trong nlnrng sue rnanh tiern tang cua ngon ngtr lap trinh C can diroc khai thac trier de.

2. Cdch sir dung COil fro

Cilng nhu cac bien khac, tnroc khi sir dung ta phai khai baa can tro, Can tro trong ngon ngO: I~p trlnh C duoc khai baa thea cu phap sau day:

Ki€u "TenBienTro;

Vi du d~ khai baa mot can tro kieu s6 thuc ta co th~ viet nhu sau: float *P; 1* P la ten cua can tro "/

M6i quan he giua can tro va bien co th~ duoc rna t,\. nhu sau:

Vi du 3-1. V oi khai b,IO :

int *Pa, Pb, x, y; x=2003; y=1999;

Pa=&x; Pb=&y;

Thl ta e6:

8(l nho

Con Ir6 Pa

I 00002 r---. ;>;;=2003

l 00006 r-+ y:1999 Con Ir6 Pb

Dja chi

00000 00002 00004 00006 00008 0000 A

Hinh 3.1. M6i quun he gilta con Iro va bie-n.

Khi can tro Pa chua dia chi cua bien x ta n6i rang Pa tro den x va ta e6 the truy xuat den bien x thong qua can tro nay. Tuy nhien de truy xuat ghi tri ella mot bien thong qua mot can tro ta phai dung dang khai baa ella ehinh con tro d6. Vi du, de gan gia tri 123 cho bien x a tren ta c6 tbe viet nhu sau:

*Pa=123; 1* "Pe chfnh la d~ng khai b<'1.0 cua contro Pa "t

Khi d6 gia tri cua ban than bien x bi thay deli urong duang voi viec dung cau lenh: x=123;

Vi du 3-2. Vi du v~ mot s6 ki~u can tro va ki~u dia chi. V 6i cdc khai bao sail .-

float *Ten1[100];

float (*T e n2)[ 1 OOJ;

float *Ten3;

, -GTNNLTC

81

float Ten4[25][1 00];

Cau lenh thtr nMt se khai 000 ra mot mdng COil Iro (phdn sal! fa se- nghien CU"u kf ve mdng) ki~u s6 thuc c6 ten 13. Tenl g6m 100 phan nr, CAu Ienh thu hai se khai baa ra mot COil tro ki~u jloat[lOO] c6 ten la Ten2 (nghia la n6 Sl! chua duoc kieu dia chijloal/ lOa)). Cau lenh thu ba dan thuan chi khai baa mot bien tro kieu float co ten l8. Tens. Con cau Ienh thtr nr dung M khai baa mot mang hai chieu g6m 25 hang, m6i hang co 100 phan nr ki€ujloat co ten la Ten4 va Ten4 dUQ'C coi la mot hling dia chi kilu jloat[IOO] (phdn sau se- gidi thiclt ki han vall de lIay). Nlnr v~y nell ta thtrc hien phep gan:

Ten3=Ten4; se bi canh baa VI ta gan sai kieu dia chi cho can tro Ten3. Ten1=Ten4; se baa 16i VI Tenl lit mot hang dia chi kieu can tro float con Ten4 cling la mot hang dia chi ki~ufloat[IOO].

Nhung cuu /¢nh

Ten2=Ten4; thi harm toan hop l¢ vi ta da gan mot hang dia chi kieu

jloat[IOO] cho mot con tro ki~ufloat[IOO].

Cdc phep totin tren can tro a) Phep cong, tril dia chi

Trang ngon ngir lap trlnh C, ta c6 tM cong, trir gia tri cua mot can tro (chill" fa dia chi cua II1qt vuug II/If] nao d6) voi mot s6 nguyen d€ cho ket qua cling HI. mot gid tri dia chi cling kiffu. D~ hieu ro dieu d6 ta hay xet vi dI,J diroi day.

Vi du 3-3. Xet dean chuang trlnh: int "Pix, "Ply, x;

float ·Pfx,*Pfy, y;

Pix= &x; /. cha Pix tro den bien x (chua dja chi vung nha cua bien x)*/

Piy= Px+ 1; r Piy se tro den bien ng uyen nam sau x tron 9 bQ n hO, c6 ngh Ia la gia tr] cua n6 duc,Jc tang IEm 2 (b~ng kfch thLlac cua bien nguyen) "!

x= Piy - Pix; /" se gim 1 cho x, tuy nhien phep cQng, nhan, chla ... thi kh6ng hop 1$ trong trLlong hop nay */

Pfy= &y; r Pfy se tro den bien thirc y */

Pfx= Pfyw1; /* Pfx se tro den bien tht,fc nam ngay truck bien y trang be? nha, c6 nghTa la gia tr! cua n6 b] gi<!lm dl 4 (bang kich truroc cua bien thirc) »]

Dieu d6 co nghia la phep cong (tri() dia chi d6i voi moi kieu COl/' tro se thay d6i tuy thea kilu dia chi rna n6 chua (kt cd kitll di'lli4u do nguiJi dung dinl: nghia),

b) Phep gdn

Ta c6 the gan cho mot con tro dia chi cira mot bien cung loai (nhu ale vi dLJ tren) hoac gia tri cua mor con tro cung Ioai khac, Vi dI,J, M con tra Piy cling tro den bien x a tren ta co th~ viet: Piy=Pix; D~ c6 th~ gan gia tri cua cac con tro khac IOiJ.i cho nhau ta phai dung toan tiI ep kieu (). Chtrong trinh sau day minh hoa each dung cua roan tir ep kieu M truy nhap Byte cao va Byte thdp cua mot bien nguyen:

Vi du 3-4. Viet chuang trinh gan gia tri cho tirng byte cua mot bien nguyen, dira ra man hinh gia tri cua s6 nguyen do.

f* ***********~**.******.*.*.**********~******~*****~************.********~***********~***** */

#incJude "stdio.h~

82

#include "conlo.h"

int rnaint) {

int BienNguyen; char *Pc;

Pc=(char*) &BienNguyen; /* Baa cho trinh bien dich biGt la ta lam vi~c voi vung nho cua bien nguyen theo tUng byte */

*Pc= 'a'; I" dUa gi<3. tr! 61h van Byte thap cua bien nguyen BienNguyen *' *(Pc+1) = 'b' I" dUa gia tr] 62h van Byte cao cua bien nguyen BienNguyen */ printf("Bien nguyen co gia tri la %X H", BienNguyen):

getchO;

return 0;

Ket qua chlJY chuang trinh:

Bien nguyen co gia tri la 6261 H

c) Phep so sanh con lro

D6i voi can tra ta co the thirc hien cac phep so sanh ==, <= ... voi cac can tra khac (CLing kiiu) hoac voi gia tri NULL (fa gia tri dtj.c biet de' chi ra rang COil tro chua tro din mi)t vung nh{t cu rhillao).

Vi dlJ. 3~5. Minh hoa cac phep so sanh can tro. X6t doan chuang trinh sau:

if( (Pa==NU LL)&&(Pb==NU LL»

printf("\n Pa va Pb chua tro den vung nho nao l"): else if(Pa<Pb)

printfr\n Vung nho cua Pa thap han vung nho cua Pb !"); else if(Pa>Pb)

printf("\n Vung, nhe cua Pa cao han vung nhe cua Pb 1"); else printW\n Pa va Pb tro den cung mot vung nho"):

cua «

- Khi mot bien tro dB: duoc khai baa nhung chua duoc gan dia chi cua mot vung nho nao do thl van chua SLr dung diroc (II ell cotinh Sir dung co !lui gay ra nhiing !OJ khong bilt truce), Vi du sau day c6 the him r6 nguyen uie nay:

char *Name, HoTenI2_5];

gets(Name);

Cau lenh nay dung ve mat cti phap nhung se phat sinh mot canh baa khi chuang trlnh thuc hien. Muc dfch cua cau lenh nay Ia doc ttr ban phim mot chuoi ki 11,1' va hru vao vung nho do can tro Name tro toi, The nhung con tro Name van chua tro den mot vung nho nao ca. Ta c6 the sira lai nhu sau:

char *Name, HoTen[251;

83

Name=HoTen; gets(Name);

- Khi mot bien tro chua tro den mot vung nho nao ta nen gan cho n6 mot gia tri NUll d~ tranh truy nhap vao nhtrng vung nho khong biet tnroc do quen gan gia tri cho n6.

3. Con lro khong kilu (con tro void)

Can tro kieu void Ia can tro dac biet co tM nhan bat ki kieu dia chi nao. Vi

du nhtr sau:

void *Px,·Py; int x=19; float y= 65; Px=&x; Py=&y;

Cac phep toan cong, trir, so sanh Va sir dung dang khai baa khong ap dung duoc voi can tro void. Trang vi d1,l4-13 cua chuang 4 ta se xem xet q1 th~ each lam viec cua loai can tro nay va trng dung cua n6 trong thirc tien.

3.2.2. Mung

1. Khai niem va dq.c trung

Mung Iii mot t~p hop co thu IE! gam mot s6 codinh cac phan tii cua cung mot kilu dii lieu nao do. Kic:u dli lieu nay co th6 la cac kieu dtr lieu nguyen thuy trong ngon ngir lap trlnh (killl integer, real ... trong ligon IIgi( Pascal; kie'/{ int , long, float. .. trong ngo» ngi"i/(ip trinh C ... ) hoac la cac kieu dfr lieu do nguoi sir dung nr dinh nghia ra.

Cdc dt;lc trung co ban ctia mdng:

- D9 dai mang tkicli thuac nia mdng va thuang ki hieu fa n) la e6 dinh, Dieu do eo nghia la khi mot mung dil diroc khai bao, ta khong the thao tac bd sling hoac IO{1i bo cac phan nr ella mango Do do, khi hru tru de d6i nrong rna e6 so luong luon bien dong thl cau true du lieu kieu mang thtrong it khi diroc sii dung,

- Cac phan nr ella mot mang phai cung ki~u. Dieu do c6 nghia Iii mang chi c6 the hru trfr gia tri eho cac loai d6i nrong cung loai rna thai, neu cac d6i nrong diroc hru trfr khac nhau, thl ta khong th~ chon mang lam cau true du lieu rna phai chon cac loai cau true dfr lieu khac.

- Moi phan tir cua mang bao gic cling duoc dac tnrng boi b6n tham so la; ten mdng, chi so', kilu va gi6. tri. Trong d6, gid tri la bi€u dien ella d6i nrong duoc luu tru trong m&i phan tir ella mango chi so' hi ,II l~ t ~t ella phan til d6 trong mango

2. Can trite luu trii va each su- dung mdng mr}t chieu (vec to) a. each khaibdo

Ki~u Ten Ma ng[ K{eh Th LIoe 1;

Trong do, Kiehl lucre se chi fa s6 phan ur (6i da trong mango

84

Vi du d~ khai baa mot mang cac s6 thuc co ten ManglOO g6m 100 phan tir ta co th~ viet nhu sau: float Mang100[100};

b. Cdu true luu tril cua vec to trong b¢ nha

Voi khai baa float at JOO}; thl trlnh bien dich se cap cho chirong trlnh irng dung mot vung nho co kich thiroc la 4 x 100 bytes lien tiip nhau trong btl nlur bat dau tir mot dia chi xac dinh nao do, dia chi nay se duoc gan cho ten cua mang HI a (co nghia rang, tell mdng la mt)l Mllg con fro chua dia chi cua phdn Ilf ddu tien trong nuing). Do d6 muon truy nhap den cac pban tir khac cua mang ta co the truy nhap thong qua dia chi nam trong ten mang thea cong thtrc sau:

Dla chi cua phan tu eo chi so i cua mang a bang a + ; (21) Chieu lang diin cua dia chi trong b(J nho

I .. ·

c. Cach truy II//(IP cdc pluin fir Clia vee to

De co the truy xuat den tirng phan tir ella mang, ta co the truy xuat thea hai each. Ctich. thu nhdt, truy xuit tnrc tiep thong qua tell mdng va chi so, Vi du de gan gia tri 10.0 cho phan tir thu 5 ella mang tren ta c6 th~ viet nhu sau: a[4]=10;

Cticn thz( hai, truy xuat thong qua viec tinh dia chi ella phan tir can truy xuat trong bQ nho, Vi du d6 dira gla tri 2003 vao pharr nr thir 9 cua mang tren day (co chi 56' i ==8) ta c6 the viet: *(a+8)=2003; trang do (a+8) se cho ra dia chi cua phan tu thu 9 cua mang, Con phep *(a+8) se cho phep ta truy xuat den 6 nho d~t tai dia chi (a+8) va do do gia tri 2003 se dtroc gan cho phan ti't thu 9 cua rnang.

Nhfmg dieu tren day co th~ viet tong quat lai nhu sau:

Voi mang a[LOO] thl cac each viet sau 13. wang dtrong:

a ho~c &a[O]

a+l hoac &a[i]

*(a+i) hoac a[i]

Vai 0<=i<100

D6i voi mang ngoai hoac mang tinh (cd trong va IIgoiii) thl ta c6 th~ khoi dau (gall giG trf ngay hic khai bdo) mot lall VelO liu: dich chuang trinli cho chung. Trang khi khoi dau cho mang ngoai hoac mang tinh ta c6 the khong can chi ro kich thuoc cua chung, Khi d6 may se danh cho mang mot khoang nho du 100 d~ thu nhan danh sach cac gia tr] khoi d[iu.

Vi du 3·6. Doan chuang trinh sau day se chi r6 each [hue khoi dau cho rnang ngoai va rnang tinh.

float MangThuc1 00[100]= {2.1, 0, 4.5, 36};

21 Neu a la rnang nguyen rhl a se chira ki6u dia chi nguyen (c6 nghia lit a+I se rro den 2 bytes tiep theo), neu a la rnang thuc thi a se chira ki~u dia chi rhirc (co nghTa la a+ 1 se tro den 4 bytes tiep theo) ...

85

int mainO {

static int MangNguyenO= {3, 5, 6, 8};

}

Cac cau lenh tren se khai bao fa mot mang cac s6 thirc co ten la MangThuc100 g6m 100 phan tiT voi b6n phan tiI dau tien duoc khoi gao cac gia tri tUC1IJ.g img Ia 2.1, 0, 4.5, 3.6 con cac phan tiI khac co gia tri la 0 va mot mang tinh trong g6m b6n phan tiT nguyen c6 ten la MangNguy"en va diroc khoi gan cac gia tri nrong Ung la 3, 5,6 va 8.

Chuy:

- Mang thirc chat la mot loai bien trong cac ngon ngir lap trinh, do do no co moi tinh chat va dac trung cua mot bien.

- Phan tir dau tien cua mang trong ngon ngu I~p trlnh C bat d£iu tir chi so o.

- Viec truy nhap mung thea each hai se duoc ung dung nhieu trong viec

truyen (!WIn s(/ fa mdng cho ham (xem chuang 4).

Vi du 3-7. Nhap vao mot day n s6 thirc (n nhap til ban pltim), tinh va dua ra man hinh trung blnh cong cua cac phan nr eo gia tri Ian hC1IJ. 4.

#include "stdio.h" #include "conio.h" #define MAX 50

/* * •• *****~*~*~~**************.*** ••• ~~~***~***************.*.*~*~****~*********.****.***** *1

int mairu) (

float DaySoIMAX], TBC= 0; int n, Dem=O,i;

printf("\nHay cho biet can nhap bao nhieu 50 n= "): 5canf("%d" ,&n);

for(i=O; i <n: ++i)

(

printW\nHay nhap gia tri cho phan tu: DaySo[%d]=", i): scanW% r ,&DaySo[i]):

if( DaySoli] >4)

{

TBC += DaySo[i]; Dem++;

}

}

printf(U\nTrung binh cong eua cae 50 co gia tri > 4 trong day la:%r, TBC/Dem); getehO:

return 0;

}

,. ****~**********.***.***.************.*****************************.****.**.*~****~***~*** */

86

Hili ltJ.p:

- Hay giai thich hoar dong cua chuang trlnh tren,

- Hay viet lai chuang trlnh tren theo each truy xuat thll 2.

Vi du 3-8. Viet chuang trlnh nhap vao tir ban pbim 12 s6 c6 gia tri nho han 80 d~c trung cho nang suat cua 12 thang roi dung ki nr ,*, M vi! bi~u do ngang len man hlnh.

#include "stdio.h" #include "conlo.h"

1* *~~~***~~*****.*******~~*.~~*************~~~*~*****************************_ ••• ********** */

int main() {

int NangSuat[12], i, j; clrscr{);

printf("\nHay nhap nang suat cua 12 thanq:"); for(i=O; i<12; ++i)

{

printW\nThang thu %d =", i); do

{

1* Chi nhap g[a tr! nhCi hen 80*/ scanW%d", &Nari g Suat[iJ);

}

while( Na ngSuat[i]>=80);

} clrscrt):

printf("\nBieu do nang suat 12 thang\n"); for(i=O; i<12; ++i)

.{

for{j=O; j<NangSuat[i]; ++j) printW%c", '"):

. printW\n");

} getchO; return 0;

}

,. .****.*************.****.****~*~~**~*********************.***************** •• ****.**~**** *'

3. Cau true luu tru va each sri dung ella mdng hal chieu (rna trdn) a. each kiwi bdo

Cting tirong tu nhu vci mang IDQt chieu, tnroc khi su dung, mang hai chieu cting phai diroc khai bao theo eli phap sau day:

Ki~u Ten_M~mg[So_Dong][S6_C9t];

Vi du cau lenh float MaTranThuc[20][30]; se khai bao mot rna tran cac s6 thuc co ten la MaTranThue g6m co 20 hang va 30 cot (600 pluin tIt).

b. Cau true luu tn? Clia ma tran trong b¢ nlur

D6i voi tna tran, nguoi ta cling su dung each thirc luu trir k€ tiep nhu d6i voi mang mot chieu, nhung tuy tung ngon ngjr lap trinh khac nhau rna viec luu tru se

87

diroc tien hanh thea tluc W uu tien hang hay tlul llf 1111 lien cot. Trang ngon ngil lap trlnh C, rna tran duoc hru tril thea thu t(r uu tien hang.

Liru tru theo tlll( tlf 1111 tien hang c6 nghia la rna tran se duoc hru tril ke tiep nhau trong bo nho, hef hang nay den hang khac, bat dau tif mot dia chi xac dinh nao do, dia chi nay se diroc chua trong ten ctla bien ma tran,

Vi d~/3.9. Minh hoa each hru tru cua rna tran cap 3x4:

Voi khai baa float a[3][4]; Thi ta nhan duoc:

aj,j ;;;;;;

J

/ /

a

Hinh 3.3. each thirc luu tril' ella ma tr~n a trong be nho

Do trong ngon nglt lap trinh C, rna tran dtroc hru trfr thea thtr tv uu tien hang, cho nen v~ thirc chat rna tran tren duqc coi nlur la mot vee fa gom 3 phan nr (cliinh Iii so' liang elia lila tr«n), moi phan tir lai la mot vee to g6m 4 so thirc lien ticp nhau (/£1 s6' Ctlt ella lila iran, 116 ciing chinh fa s6' phdn flr tren m6i "ill/g).

Vi the khi ta vie't a se cho dia chi cua phan tir dau tien thuoc hang thu nhat (ph6n t/r a[O][O}) ella rna tran a. Nhung a+I lai cho dia chi ella phan tlr dau tien thuoc hang tlnr 2 (plu'in rtt a[I][O]) cua rna tran, C6 nghia ia ten rna tran a trong tnrong hop nay se 13. mot li&ng COil Iro chua kie'u dia chijloat[4].

Chinh VI vay, muon tinh diroc dia chi ben trong bo nho cua phan tir 6 hang c6 chi s6 iva cot c6 chi s6 i cua rna tran tren (chinl: la pluin lIt ali) Uj) phai bdo cho trlnh bien dich Turbo C biet la ta dang muon lam viec voi kilu dia chi float (elilf khbng phdi kie'u dja chi float/4j) bang phep ep kie"1I nhu sau:

(float *) a + i *4 + j

c. C ach truy IIh«p de'll tung ph611 rt'r Clia lila trdn

Tuong tu nhu vee to, ta ciing c6 the truy xuat cac phan tir cua rna tran bang hai each, Cach tii« IIhot d6 13. tnty xudt true tilp thong qua tell lila trdn va chl so' dong, chi s()' qJt thea cu phap nhu sau: a[2J!3} = 2003. ;' voi cau lenh nay gia tri 2003 se duoc chuyen vao phan nr 0 hang (hu 3 va c¢t thCr 4 cua rna tran, Cacti th(r hai 13. truy xuat thong qua dia chi cua tung ph an tlr trong rna tran, Tuy nhien, ngon nglt lap trinh C khong cho phep lay dia chi true tilp cua mot phan tir cua rna tran thong qua toan nr lay dia chi & tngoai tn'r lila tr«11 nguyen). Vi du chuang trlnh diroi day nham vao so lieu cho mot rna tran so thirc khi chay se cho mot thong bao 18i nhu sau :

scanf: floating point formats not linked Abnormal program termination

Vii chting ta khong ,M thirc hien tiep clurong trinh nhu du kien.

88

Vi du 3·10. Vi du sai ve viec truy nhap cac ph fin tir cua rna tran.

#include~stdio.h~ int mainO

{

float a[1 0][51; int i, j;

for(i=O; j<10; ++i) I" xet tat ca cac dong tCI dong 0 den dong 9 "! for(j=O; j<5; ++i) t" vao s6 H~u cho fUng phan ta cua moi dong "t {

printW\nHay nhap du lieu cho a[%dJI%d]= ", i, j); scanf("%f ,&a[i]Un;

}

return 0;

}

1* *.*.**************~* •• *.*~*****.**~*******~~*******~**********~*~******~~********~.****** */

D~ giai quyet diroc van de nay. ta co hai giai phap, Gidi phap tlul: nlidt Ia dung bien trung gian. Theo each nay ta co the viet Iai doan chuang trlnh nhu sau:

Vi df!. 3·11. Su dung bien trung gian de nhap du lieu cho rna tran.

1* *******.******* •• *******.*.*~***********~*****.***** •• **********.**~********.*~********~* *j

#include"stdio.h" #include"conio.h"

/* *******************************.*************-*************.*.**~****.****~************** *{

int rnaint) {

float a[10][5], tg; int i, j;

for(i=O; i< 10; ++i) 1* xet tat ca cac dong tCI dong 0 den dong Q *' for(j=O; j<5; ++j) 1* vao s6li~u cho tung phan tll' cua moi dong '" {

printf("\nHay nhap du lieu eho a[%d][%d]=~, i, j); scanW%f,&tg); r nhap dG' Il~u vao bien trung gian '" a[imJ = tg;

}

for(i=O; i<10; ++i) r xet tat ea cac dong tit dong 0 dfin dong 9 */ _ forU=O; j<5; ++i) 1* hi~n thi tung phan tll' cua moi dong "/ pri ntf("a [%dJ[%dJ= % 1 0 .2f, i, j, a [i][j]);

getchO; return 0:

}

'* ~******.*~****.****************.**~.***** •• * •• ~~***.***********.**~*********~************ */

Gidi phap thit hai ia truy xuat thong qua viec tfnh dia chi cu th~ ella tung phan til trong rna tran nhtr dii trlnh bay i:J cong thirc tren va doan chuang trlnh co th~ dtroc viet lai nhu sau:

Vi du 3·12. Nhap du lieu cho ma tran thong qua viec tfnh dia chi.

1* *****.*****.***~*****.*******.*****.*********.*.****************************************- */

#incJude"stdio. h" #include "can io.h"

89

/* ~*******~.*****.*.******************************.***************.*** •• ~**.*~**.*~******** *'

int mainO {

float a[10][51, tg; lnt i, j;

for(i=O; i<10; ++i) l" xet tat ca cac dong tu dong 0 d~n dong 9 *' fortj=O: j<5; ++j) 1* vao s6li~u cho tLtng phan tLr cua moi dong "! {

printf("\nHay nhap du lieu cho af%dJ[%d]=", i, j); scanW%f', (float") a + i" 5 +j );

}

for(i=O; i<10; ++i) 1* xet tat ca cac dong tu dong 0 den dong 9"/ forU=O; j<5; ++i) 1* hien th] tLtng phan ttr cua mOi dong "l printWaf%d][%d}= %10.2f', i, j, a[i1UD;

getchO; return 0;

}

,. ~**~********.********.****~****.*******~.******.**~****~~***~**************~**~* •• *~ •• *** */

fJtJ'i vOt ma tran ta ciing co the khOi dli'u thea cu pJuip sau day: int MaTranNguyenIJ[6}= {

{1,2,3}, {4,5}, {6,7,8,9}

}; float MaTranThucI1 0J[1 01= {

{10,11}, {1,3,6,8}, {O}

};

Chuy:

- Khi chi ra kfch thiroc mang, thi kfch thiroc nay phai Ion han kich thiroc cua bo khoi drill.

- Khi co milt kich tluroc vang mat, thi kich tlnroc vang mat phai narn ben tay

trai nhat (vi du nhu kluJi dati cho MaTranNguyeli J tren), - B¢ khoi dau cua mot mang kieu char co the:

+ Hodc fa datil! sdcli cdc ki til

+ H oac fa 1n9t Mllg XQIJ ki tu.

Vi du: char Name[1={'M',T,'n','h','\O'}; hoac

char NameU="Minh"; deu cho ket qua gicng nhau.

Vi d~ 3-13. Viet chuang trlnh nhap rna tran vuong A cap /I, cac phan til la s6 nguyen. Dira rna tran tam giac dirdi va rna tran tam giac tren cua A fa man hinh. Cac dir lieu diroc nhap tCr ban phfrn,

/* *~******.**~*.********~*.****.****.*****.*********.***.*~*****************.************** */

#include "stdio.h" #include "conio.h"

1* *~*****~*.*** •• *********************** •• **** •• ****.***.***.*****.********.*~*****~.**~~** ~I

int main()

90

{

int a[301[30J, i, j, n: clrscrt):

printW\nHay nhap so hang (cot) n= "); scanf("%d~, &n);

printf("\nVao ma tran A\n");

10r(i=0; i<n; ++i)

for(j=O; j<n; ++j) {

printf(" A[%dJ[%d]= ", i, j);

scanf("%d", &a[i](j]); t" vi day la ma tran nguyen'"

}

clrscr() ;

printf{"\nMa tran tam giac tren (gam ca duang cheo chinh) nhu sau \n"); for(i=O; i<n; ++i)

{

for(j=i; j<n: ++j) 1* ch r xet cac p han tll' tren duo-ng cheo chfnh *1 {

gataxy{8* (j+ 1). 3+i); printf{"% 7 d", a[im});

}

printf{"\n"); /* het m(lt hang cua ma tran *1

}

printf{"\nMa tran tam giac duoi (gam ca duong cheo chinh) la:\n\n"): 10r(i=0; j<n; ++i)

{

10rO=0; r= i: ++j) 1* chi xet cac phan tll' duoi duong cheo chfnh*1 pri ntf(" % 7 d", a[i](j]);

printf("\n"); r sang hang tiep thea */

} getch(): return 0;

Vi d~ 3-14. Viet chuang trinh nhap nr ban phfm rna tran T kfch thuoc III x /I

{1 neu u, - > 0 I,j

(m<=20, 1l<=35). TInh rna tran S cung kich tluroc sao cho: Si,i = 0 neu Ui,j = 0 -1 neu u. , < 0 I,J

Dira ra man hlnh rna tran S thea dung hang. cot,

#incrude "stdio.h" #include "conio.h"

int mainO {

float T[20][35]. a, b: int S[20](35], i, j, m, n: clrscrt):

91

printf("\nNhap kich thuoc rnanq m,n = "): scanW%d%d", &m, &n);

printW\nNhap mang T:\n");

for(i=O; i<m: ++i)

for(j=O; j<n: ++j) (

printf("\nT[%d][%d]= ", i, j); scanW%f", (float-)T+ i*35 + j); if( TIi] [j] >0)

S[i][j]= 1: else if (T[i]Ul<O) S[i][j]= -1;

else

S[i][j]= 0;

}

printf("\nKet qua S la:\n"); tortl=O: i<m;++i)

{

printf("\n") ;

for(j=O; j<n; ++j) printf("% 3d", Sri] [j]);

} getch(); return 0;

}

,~ *****~**********.*** •• ** •• *********~********* •• *************~***********************.~*** */

4. Han che cl;a vi¢c sit dung mung

Xet bai roan cong hai da thUc bac n hai fin s6 x va y. Nhan xet rang, khi cong hai da thirc ta phai tim kiern cac s6 hang cung bac ella x va y r6i cong cac h¢ sc lai voi nhau. Nhu vay, M viec c¢n~ hai da thuc co the lam viec mot each hieu qua, ta phai co each bieu dien nao d6 de phan biet duoc cac bien, he s6 va s6 mil trong moi da thirc thanh phan. C6 nhieu each bieu dien khac nhau eho da thirc, trong d6 c6 mot each, wang d6!. hieu qua va de sir dung ,d6 la ,du~ft m,': tran d~ bieu die? the,o nguyen tac sau: moi rna tran vuong cap n dung de bieu dien cho mot da thirc cap (n-I) ella x va y, trong d6 moi phan tu a hang i CQtj cua rna tran se hru trO'M s6 cua phan tu r y' ella da thirc. Vi du cac rna tran sau dung de bieu dien eho cac da thirc:

P(x,y)=8 X4 +6yJX2 +3y2x3 + xy -1
Q(x,y)=4x4 + 12y2XJ + 7 y2x2 + xy +11
P(x,y) + Q(x,y)
0 2 3 4 0 2 3 4
0 ·1 0 0 0 0 0 11 0 0 0 0
1 0 1 0 0 0 I 0 1 0 0 0
2 0 0 0 6 0 +2 0 0 7 0 0
3 0 0 3 0 0 3 0 0 12 0 0
4 8 0 0 0 0 4 4 0 0 0 0
llinh 3.4. M6 tii phep cong hai da thuc hai an dung rna tran, 92

Bai toan cong hai da thirc gio day da chuyen thanh bai toan cong hai rna rran cung cap (co the'rnJ r¢ng hili roan thanh tru, nluin, chia ... hai da tlurc) va ket qua phep cong nhu sau (hinll 3.5.).

0 2 3 4
0 10 0 0 0 0
1 0 2 0 0 0
C(X:,y) '" 2 0 0 7 6 0
3 0 0 IS . 0 0
4 12 0 0 0 0 Hinh 3.5. K~I qua phep cong hai da thirc du6"i dang rna rran,

Tir d6: C(X,y)=P(X,y)+Q(X,y)= 12x4+6y3 x2 + 15 y2X3+ 7 y2X2+2xy + 1 0

'lu ;lh~n tMy, viec dung mang d~ bieu dien eho da thirc nhu tren d1l lam giam di nit nhieu do phuc tap cua bai toano Tuy nhien, co nhtmg han che de nhan thay nhu sau:

- MOi mang cap nxn chi co the bieu dien duoc cho mot da [hue cap tn-L) cua x va y, do do han che pham vi xtc li.

- Neu cac da thirc dUc;1C bieu dien la kh6ng day du (vi du da (hue P(x,y) = x'(}(J(J + y), khi d6 ta phai dung mot ma tran 1001 x 1001 phan tir M hru tnr hai he so caa P(x,y), con alt ca (1001 x 1001 - 2 ) phan tll con lai deu c6 gin tri bring khong va kMng duoc Sll dung den. Dieu nay se gay ra mot su lang phi bo nho do tfnh co dinh cua mang, D~ e6 tM khac phuc ducc cac nhuoc di~m cua mang, chung ta se tiep tuc nghien cuu mot cau true dil lieu d~c tnrng tiep theo trong muc 3.3.4, d6 la cau true dil lieu kieu danh sach m6c noi.

5. Chuoi (String) va xrlli chuoi

CI1ll6i hay xau ki tlfla mot mang kieu char ket thiic bang kf tu '\0'.

Cling gi6ng nhu ten mango ten chuOi cling Ia mot hang con tro chua dia chi cua lei tt.! dau tien trong chuOi.

Vi du, de nhap tu ban phim ten cua mot nguoi ta can dung mot rnang kieu kf

tu voi doan chuang trlnh sau:

char Ten[30];

printf("\nHay nhap ho va ten:"); gets(Ten);

Vi du 3-15. Viet chuang trlnh nhap ttr ban phfm mot cau (it fum 80 ki t~r) r6i d€m xem trong cau vira nhap c6 may tit (xau kluu: r6ng khOng dura dall each)?

Gidi. De viet diroc chirong trlnh ta can dung them ham:

int isspaceiint KyTu) khai bao trong ctype.h dung d~ ki~m tra ki tu KyTu c6 phai la dau each hay khong? ham tea v~ gia tri 1 (dlillg) neu KyTu la dau each va trii v~ 0 neu nguoc lai, va ham int strlen(char *s) khai bao trong string.h dung M tfnh dQ dai cua chuoi s.

1* *********************.** ••• ********************************************* •• ***********.*** */

#include "stdio. h" #include "conio.h"

93

#include "ctype.h" #include "strinq.h"

1* ***~***********~~****~*****~************~********~******************~~**~~*******.** •• *.* */

lnt malnt) {

char Cau[81]; lnt L, l, Dem=O; clrscrt):

printW\nHay nhap mot cau khong qua 80 ky tu\n"); gets(Cau);

L= strlen(Cau);

Cau[L]= ' '; /* dung ki thuat d~t Ifnh canh d~ danh dau sir ket thuc tim "t Ca u[L + 11= '\0' ; /* f)anh dau lal Sl,J' ket thuc cua chuai * /

for(i=O; i<=L; ++i)

if( !isspace(Cau[i])&&isspace(Cau[i+ 1]))

Dem++;

printf("\n\nSo tu trong cau la: %d\n", Dem); getch();

return 0;

Vi du 3-16. Viet chuang trmh nhap tu ban phfm mot xau kf tu sau d6 nhap vao mot kf ttf bat kl roi dern s6 hrong ki tu nay c6 trong xau vira nhap, thong bao ket qua ra mao hinh.

/* ******~~***~**********~*************.*********************~~***********.*****.*******.*** */

#include "stdio.h" #include "conio.h" #include "string. h"

int mainO (

char Xau[80], Ch; int L, i, Dem=O; clrscrt):

printf("\nHay nhap mot xau khong qua 80 ky tu\n"); gets(Xau);

printW\nHay nhap ky tu can dem\n"); scanf("%c", &Ch):

L=strlen(Xau); for(i=O; i<L; ++i)

if(Xau[i]==Ch)

Dem++;

printf("\n\nSo ky tu %c trong xau la: %d\n", Ch, Dem); getchO;

return 0;

}

'* **************.******.***************************************.*************~~**~***~***** */

Vi du 3·17. Viet chuang trlnh liet ke mot bang MENU, du lieu nhap vao tir ban phim g6m:

94

- Ten tieu de MENU (kh6ng qua 30 ki til).

- S6 lirong cac MENU (n <20).

- Noi dung tirng MENU (klu5ng qua 30 ki tl!).

Yeu cau chuang trinh phai hien len man hlnh cac n¢i dung mini trong mot khung chi! nhat. Kich thtroc cua khung chu nhat phu thuoc vao n va d¢ dai cac xau,

r **,****,*,~* •. ***"*****,*"***,****'1Ir*.*.*" ••• ** •• *******'*'********.** ••• ****'***'***1!*'*.***.* .... **** *1

#include "stdio.h" #inelude "conio.h"

#include "string.h" _

1* ***********'***~********.************.** ••• *****************.*******.*******~.*1!***.* •• *.* */

int mainO {

char TieuDe[30], NoiDung[20][30]: int Max, x, y, n, i;

elrser() ;

printf{"\nHay nhap Tieu de cho MENU\n"); gets(TieuDe);

Max= strlen{TieuDe);

printW\nHay nhap so luong MENU n= "); seanf("%d", &n);

fflush{stdin);/* Lam sach dong nhap, loai be kr tl,f xu6ng dong do ham seanf de lai, Neu kh6ng cau I~nh gets 0 sau se b] tr6i */

for{i=O; i<n; ++i)

(

printf{"\nN oi dung MENU %d la: ". i); gets(NoiDung + i);

if(Max< strlen(NoiDung + i)) Max= strlen(NoiDung + i);

} elrscr() ;

Max+= 4; /* dQ rQng eua khung */ x=(int)( (80- strlen(TieuDe ))/2+0.5); y=2;

gotoxy(x ,Y);

puts(TieuDe); I*£ll.ta chu6i TieuDe ra man hlnh sau d6 xu6ng dong */ gotoxy(x, y+1);

for(i=1; i<=strlen(TieuDe)+1; ++i)

putchar('=');/* ve khung dlloi tieu de */ x=(int)(80-Max)/2);

y=4;

gotoxy(x, V); r chuan b] hien th] n¢i dung cua Wng rnuc Menu */ for(i= 1; i<=Max+5; ++i)

putchar('*'); l" ve khung bao tren '" for(i=O; l-en: ++i)

{

gotoxy(x, y+i+1);

printf("" %d. %s", i, NoiDung + i); gotoxy(x+Max+4, y+i+ 1); putst":"): r VEl khung ben phai ./

95

}

gotoxy(x, y+n + 1); for(i=l; i<=Max+5; ++i)

putchar('*'); '* ve khung dllCJi ., getchO;

return 0;

}

1* *******.~~*************.***** •• ***~********.*~********.****~***** •• *******.**.****** •• *** *'

Bili tap: Chay va phan tich hoat dong cua chuong trinh tren,

Vi du 3-18. Viet chuang trinh nhap vao ill ban phim mot van ban sau d6 chen VaG van ban do tai vi trf thu i mot xau moi. Dua ket qua ra man hinh.

#inclu de "stdio: h" #include "conio.h" #include "strinq.h"

/* ********~***.********* •• ********~.*****~*************~**.************.*.***~~*.*.******** -,

int mainO {

char VanBan[80], Xau[30]; int i:

clrscrt):

puts("Hay nhap mot van ban:"); gets{VanBan);

puts("Hay nhap chuoi can chen"); gets(Xau);

puts("Hay nhap vi tri chen"); scanf("%d", &i):

clrscr();

puts("Xau ban dau la:"); puts(Van Ban);

if(i> strlen (Van Ban))

{

strcat(VanBan, Xau);I* Ghep chuai Xau vao sau chu6i VanBan*1

}

else

{

char Luu[80]; .

I" Copy cac kf h,l con lal trong xau VanBan bat dau W vi trf ttur i cua xau *1

strncpy(Luu, VanBan+i, strlen(VanBan)-i+ 1 );-

'* Gan them dau each VaG sau i kf tll dau tien cua xau VanBan tnroc khi ghep, sau d6 cat xau t9i vi' tri do bang kl tl,f ket thuc·1 VanBan[i]= ' ':

VanBan[i+ 1]= '\0';

1* Ghep Xau vao sau i kf tl,f cua xau Van Ban "t strcat{VanBan, Xau);

t: Tach cac doan ghep bang dau each ./ i= strlen(VanBan);

VanBan[i]= ' ';

VanBan[i+1]= '\0';

96

/* Ghep phan con I~i cua xau Van Ban vao chuai */ strcat(VanBan, Luu);

}

puts("Van ban sau khi chen la"); puts(Van Ban);

getch():

return 0;

}

I~ ** •• ************~****************~~*~~*****.********.~*~~******.******~*~~***~******.**~* ~I

Nhan xet:

Chuang trinh tren day drr baa g6m nhicu thao tac dac trung cho vice xu ll X<l.U kf tl! (rang ngon ngir lap trinh C nhu vice ghcp xau (dung ham char* strcattchar *ChlioiNhall, char *ChuoiGhep), chep II ki tu dau tien tir xau ngu6n sang xau dfch (dung ham char" strncpyichar * XauDich, char+ Xauivguon, n)) ... (xem them plu: luc l/J) va dac biet Ja each dieu khien su ket thuc ella moi xau.

Hili t(lp: Xet mot doan ella chuang trlnh tren strnepy(Luu, VanBan+i, strlen(VanBanH+1):

VanBan[i1=' '; VanBan[i+11='\O':

Dieu gl se xiiy ra khi hai cau lenh dung sau cung vang mat? Hay chay thir chuang trinh trong tnrong hop do va so sanh voi nhan xet cua ban thanl

Chu j:

Ta khong the' dua true tiep mot hang kf ttl (m¢t xdu troug ddu "") vao mot

hie;/ XciII duoc, Vi du cac cau lenh sal! day la khong hop le:

char HoVaTen[30];

HoVaTen= "Nguyen Van A"; r Sai */

Do lIoVaTen Hi mot hang can (ro chua dia chi dau cua vung nho cap pha t cho bien xau, "N gllye/l Vall A" ciing la mot hang con tro chua d ia chi cua vung nho hru chuoi "Nguyen Vall A". Ta kh6ng the gan mot hang can tro nay cho mot hang can tro khac duoc. D~ lam duqc dieu do ta c6 th~ gi.l.n thong qua CC1 che khoi dau, thong qua ham scanf, thong qua can tro hoac dung cac ham thao tac tren chuoi nhu vi du sau:

char HoVaTen[30]; strcpy(HoVaTen, "Nguyen Van A");

6. Lien h¢ giiia con tru WI mdng

Trang ngon ngfr lap trinh C, can tro va mang c6 m6i lien he mat thiet voi nhau. Ta dii biet rang ten mang la mQt hang can tro chua dia chi ella phan tir dau tien trong rnang, do d6 cac diu lenh sau day Ill. hoan toan hop le:

int MangNguyen[30], *Pi;

float MangThue[30], "Pf;

Pi= MangNguyen; /" Cho Pi tro toi vung nho ella mang MangNguyen */ Px= MangThue; /* Cho Pf tr6 toi vung nhd ella mi:mg MangThuc "t

97

01-GTtlNLTC

Sau cac cau Ienh tren thi :

Pi + i se tro toi phan ti'r M ang N guyen] i J . Pf + i se tro toi phan tir Mangl'hucji],

Va d6 truy nhap den cac phlin tir nay, cac cau lenh sau la tuang duang nhau:

MangNguyen[i] =10; *(Pi + i)=10; -(MangNguyen + i)=10; va Pi[i]=10; hose MangThuc[i]=2.1; -(Pf + i)=2.1; "(MangThuc + i)=2.1; va Pf[i]=2.1;

Tuy nhien van de tr6 nen phirc tap han khi si'r dung can tro voi mang nhieu chieu, Vi du v6i cac CaU lenh:

float -Pf, MangThuc[20][30]; Pf = (f1oat*) MangThuc:

- Thi nhirng cau lenh sau day:

MangThuc[i]m (22) =3.5; Pf[i]U]=3.5; *(Pf + j*30 + j)=3.5; *((float*)MangThuc + i*30 +j )=3.5; se nrong duong voi nhau.

7. Mdng con lro

Mung con tro la mang dac biet rna moi phan tir cua n6 ia mot can tro dung M chua dia chi cua mot bien nao d6 va n6 e6 day du cac tinh chat cua mot mango Mang can tro duoc khai bao theo mau sau:

Kieu *Ten Mang[Kfch Th LJOC Mang];

Vi du 3-19. Cau lenh double *MangConTroJ[lOO] se khai bao mot rnang gorn 100 phan tir, moi phan ti'r Ia mot can tro kieu double c6 the dung chua kieu dia chi double.

Chi; s. can phan bier khai bao tren voi khai bao double (*Mang)[100]: dung M khai bao ra mot con tro c6 th6 chua diroc kilu dia chi doubler 100].

3.2.3. Cau true iStruct) va hop (Union)

De luu trCi' va xu Ii thong tin trong may tinh ta can dung den cac bien va mang, tuy nhien moi bien lai ehi chua diroc mot gia tri cho mot kieu xac dinh, Con mang e6 tM xem la tap hop cua nhieu bien c6 cung mot ki~u gia tri va diroc bi6u thi bang mot ten. Trong thuc te, viec hru till va xu Ii thong tin khong phai don thuan chi thao tac tren mot gia tri boac tap cac gia tri cung kieu, rna doi hoi c6 su t6 hop cua nhieu kieu du lieu thanh phan trong cung mot d6i urong xu Ii. Ch~ng han, d~ XU Ii thong tin lien quan den mot d6i tuong lilian vien ta can cac kieu dCi' lieu nhu rna s6 nhan vien, ten, dia chi, ngay sinh, que quan, mire IUO'Ilg ... va cac du lieu nay pbai diroc XII' li thong 1I1Id! de dam bao tfnh toan ven dCi' lieu, Cac d6i nrong du lieu loai nay rat da dang , phong phu va thirong do ngiroi lap trlnh nr djnh nghia ra tuy theo nhu cau cua ho, Cac d6i nrong dCi' lieu nhu vay trong ngon ngu lap trlnh C ngiroi ta goi la cac cdu true (struct - tuoug t{t ball ghi trong Pascal) va hop (union). Mac du cau (rue va hop c6 nhieu diem nrong dong, song chung cling c6 nhtrng d~c tnmg rieng va duoc sir dung cho cac muc dfch khac nhau. Trong phan nay ta se nghien ciru ki dac diem cua tung loai,

22 V6i O<=i <=19 va a <=j <= 29

98

1. ca« true (Strucn

au true Iii mot ki~u dfr lieu do nguoi sii dung nr dinh nghia ra ban g6m nhieu thanh phan, rnoi thanh phan e6 th~ la mQI bien, mang hay con tro co kieu dii duoc dinh nghia san (rang ngon nglr (nliu inr.float , double ... ) hoac lai Ia mot edtl true (/lay 'Wp) nao d6.

CU phap khai baa:

struct [HmKi~uCauTruej {

t" Khai bao cac thanh phan dG' Ii¢u a day;·/ } [Danh sach bien];

Trang d6, struct HI ter kh6a dung d6 dinh nghia C[IU true. TeJlKie'uCliilTnic la ten bat kl do ngiroi h}p trinh d:)t ra thea quy tac d~l( ten trong ngon ngf! h~p trinh C.

Vi du 3-20. Dci djnh nghla ra cau true dir licu dung de luu trf! cac thong tin ella thf sinh trong mot kl tuy~n sinh ta co th~ viet nhu sau:

struet Date

{

int Ngay; int Thang; int Nam;

};

struet ThiSinh {

char SoBaoDanh[ 10]; char HoVaTen[30j: char QueQuan[501;

, struct Date NgaySinh; float DiemTaan;

float DiemLy;

float DiemHaa;

} TS1, TS2. ~DS;

struet ThiSinh TS3,TS4, DanhSaeh[501, ~Pts;

Mot cau true sau khi dinh nghia xong ta co the sir dung n6 M khai baa cho cac bien, mang va can tro, Co hai caclt de khai baa bien, mang hay can tro kieu cau true, do HI. khai boo nuc tiel) trong hie djnh nghia (nhu bien TS1, TS2 va COli fro DS J tren) va khai baa sau khi da: dinh nghia (nliu hiill' TS3. TS4, mdng DallflSaehj50j WI COli tro Pts I/O(ie bh;J, NgaySillh if tn?n).

Mot bien, mang hay can tro cau true sau khi khai baa se co ddy d,i moi tinh chat nhu cac bien, rnang hay con tro thong thirong. Ngoai ra n6 con e6 them mo; vai due tnrng kh.ic nhu sau:

a} Cdc tliao Ide 'rell II/(!t edll true

- Truy IIh~ip dell cdc thunh pha'1l ella cal, true : D€ truy nhap den I11Qt thanh phan ella mot bien hay phan tu lhu i mang kieu cau true ta co th~ viet nhu sau:

TenBienCauTrue.TenTh<,mhPhan va

99

Sign up to vote on this title
UsefulNot useful