You are on page 1of 125

Chng 1.

CHNG TRNH C N GIN


Bi 1. CC KHI NIM C BN

1. Cc phn t c bn ca ngn ng C
Tp k t Tn gi, t kho - T kho dng khai bo chung: asm, pascal, cdecl, typedef, const, enum, extern, static - T kho dng khai bo kiu: struct, double, float, int, char, long, far - T kho iu khin: if, else, do, while, for, return, break, continue, swith, case - Cc t kho khc: interrupt, sizeof, void

2. V d chng trnh C n gin


V d 1: #include <stdio.h> /* su dung thu vien vao/ra chuan */ void main(){ printf(\n Hello! \n Glad to meet you); getch(); } (Ngt lnh xung dng th thm du / trc dng trn V d 2 #include <stdio.h> void main() { float a,cv,dt; printf(\n nhap canh hinh vuong :); scanf(%f,&a); cv=a*4; dt=a*a; prinf(\n chu vi hinh vuong la: %5.1f \n / dien tich hinh vuong la: %5.1f , cv,dt); getch();}

3. Vo ra n gin
3.1. a d liu ln mn hnh printf(dng iu khin, bt1, bt2, ...); Dng iu khin gm: - K t iu khin: \n, \t - K t c t : %f, %10.3f, %d, %8d ... - Cc k t thng bo. 3.2. Nhp d liu t bn phm scanf(dy k t c t kiu, dy cc a ch bin);

Bi 2. KIU D LIU, HNG , BIN V BIU THC.

1. Kiu d liu
stt 1 Kiu char signed char unsigned char 2 int unsigned int long (int) unsigned long (int) 3 float double long double 4B 8B 10B 4B 2B Phm vi 1B -128-127 0-255 -32768-32767 0-65535 -2.147.483.648 2.147.483.657 0->4.294.967.295 3.4E-38-3.4E+38 1.7E-308-1.7E+308 chnh xc n(8) chnh xc kp(16) -> Kch thc Ghi ch 0-31: iu khin 32-127:hin th tren mn hnh v my in 128-255:trn mn hnh

3.4E-4932-1.1E4932 s ch s c ngha(18)

2. Hng
#define tn_hng gi_tr V d: #define heso 10 #define PI 3.14 #define longint 12345678 #define he8 0347 #define he16 0xA9 Ch v hng k t 1) a l hng k t c lu tr trong 1B - Gi tr ca a l m ASCCI ca ch a, vy gi tr ca a l 97

Gi tr ca 9 l 9-0 = 57-48

2) Hng k t a cn c th vit di dng \141 du \ khai bo mt k t c bit. a c gi tr 97 h 10, c gi tr 0141 h 8 3) Cc hng k t c bit: \n: xung dng \0:k t NULL: \0 \t:Tab \b:Back space \r: CR v u dng \f:LF sang trang 4) Phn bit 0 l hng k t ng vi ch s 0 , c gi tr 97; \0 l hng k t ng vi k t NULL c gi tr 0 5) Hng k t thc cht l s nguyn printf(%c, %c, 65,66); s in ra AB 6) Phn bit hng k t v hng xu k t a : l hng k t gm mt k t a a : hng xu k t gm 2 k t a v k t NULL (tc \0). K t \0 c C t ng gn vo cui hng xu k t nh du kt thc xu Ha noi l hng xu k t gm 7 k t 5 ch, 1 cch v null l hng xu k t rng, ch gm mt k t NULL

3. Kiu enum
Mc ch: to cc macro nh define 1. 2. 3. 4. enum enum enum enum tk {pt1, pt2, ... } tb1, tb2, ... ; tk {pt1, pt2, ... } ; {pt1, pt2, ... } tb1, tb2, .... ; {pt1, pt2, ...} ;

Dng (1) c 3 chc nng: a. nh ngha cc macro pt1, pt2, ... lm lt c cc gi tr l 0,1,... b. nh ngha kiu enum c tn l tk, sau ny c th nh ngha bin kiu enum dng: enum tk x,y,z; c. Khai bo cc bin kiu enum c tn l tb1, tb2, . - Cc bin kiu enum thc cht l cc bin nguyn c cp pht 2B, nn c th nhn gi tr nguyn bt k. - Mc ch ca enum l to cc macro (thay th) cc kiu v cc bin gi nh Dng (2) : c cc chc nng (a) v (b) Dng (3) : c cc chc nng (a) v (c) Dng (4) : c chc nng (a) V d: #include <stdio.h> main() { enum {T0,T1,T2}; enum DAY {cn,t2,t3,t4,t5,t6} ng1; enum DAY ng2; int i,j =2000, k = T2; i=t7; ng1=-1000; ng2=j; printf(\n ng1 =%d ng2 = %d i = %d, ng1,ng2,i); printf(\n k =%d T1 = %d , k,T1); }

4. Bin
tn_kiu tn_bin;

1) 2) 3)

V tr khai bo : ngay sau { ca main, trc mi cu lnh Khi to cho cc bin Ly a ch ca bin : &tn_bin

5. Mng
1) Khai bo mng gm cc thnh phn: kiumng, tn mng, s chiu, kch thc mi chiu: kiu_mng tn_mng[kchthc] kiu_mng tn_mng[kchthc1] [kchthc2] 2) V d int a[10]; float b[5][7]; 3) Ch : - Cc phn t ca mng c cp pht trong vng b nh c a ch lin tc - &a[i] l a ch ca phn t th i - vit: a hoc @a[0] : l tn mng biu th a ch phn t u tin ca mng, cng l a ch ca mng.

6. nh ngha kiu
- C dng t kho typedef nh ngha kiu: - Khai bo: typedef kiu_chun tn_kiu ; - S dng: tn_kiu tn_bin1, tn_bin2; - V d: Khai bo: typedef int mang[50]; typedef float mt53[5][3]; typedef enum {T1,T2,T3} T; S dng: mang x,y; mt53 a,b;

T t;

7. Biu thc
7.1. Php ton s hc - 2 ngi: +, -, *, / , % (chia ly phn d) - 1 ngi: - (php ly i) 7.2. Php ton bt & : and | : or ^ : xor (ng tnh b hu, khc tnh th tn ti) 1 ^ 1 = 0 ^ 0 = 0; 1 ^ 0 = 0 ^ 1 = 1) 7.3. Php ton quan h ==, !=, > , <, >=, <= 7.4. Php ton logic ! : not && : and || : or 7.5. Php ton tng gim ++n hoc n++ : tng 1 n v cho n --n hoc n-- : gim n 1 n v ++n : tng n trc khi dng n++: dng n trc khi tng. v d: int n=5; int x = n++ ; vy x == 5, n ==6 int y =++n; vy y==6, n==6 7.6. Th t u tin cc php ton 1) () [] -> . 2) ! ~ & - ++ -3) * / %

4) + 5) << >> 6) < <= > >= 7) == != 8) & 9) ^ 10) | 11) && 12) || 13) ?: 14) = += -= *= /= <<= >>= &= ^= |= 7.7. Biu thc iu kin varible = condition? value1:value2 7.8. Php chuyn kiu V d int a; float b; a = (int)b; - tnh chnh xc gi tr ca php chia 2 s nguyn m v n , ta vit ((float) m)/n - i gi tr float sang gi tr int ta p dng dng (int)(r+0.5)

Bi 3. KHI LNH, HM V PHM VI HOT NG CA BIN.

1. Khi lnh v phm vi hot ng ca bin bn trong v bn ngoi khi


1) Khi lnh: { lnh_1; lnh_2; } 2) Bin trong v bin ngoi - Bin trong mt khi ch c phm vi hot ng trong khi cha n, k c vic cp pht b nh - Bin ngoi mt khi c phm vi hot ng trong khi v k c trong khi con ca khi (nu trong khi con c tn bin ). - Bn ngoi mt khi khng dng c cc bin trong khi con ca n k c trong cc khi khc. V d:
#include <stdio.h> #include <conio.h> void main(){ int x=5; {int y=x+1; printf("\nx = %d, y = %d",x,y); } printf("\nx = %d",x); /* printf(" y = %d",y); lenh nay sai*/ getch(); }

2. Hm
1) Hm l n v c lp trong chng trnh. Khng c hm con trong mt hm. Trong hm c th c cc bin cc b. 2) Hm main() l hm bt buc v gi thc hin cc hm khc. 3) Xen gia cc hm c th c khai bo dn hng bin dch

4) Vic truyn d liu v kt qu t hm ny sang hm khc thc hin bng cc cch: - S dng i - S dng bin ngoi, mng ngoi, bin tnh ngoi, mng tnh ngoi. V d : Minh ho vic xy dng hm tnh gi tr a thc f = ax2 + bx + c v s dng hm ny trong main(). Cch 1: S dng i
#include <stdio.h> #include <conio.h> long f(int,int,int,int ); void main(){ int a,b,c,x; long p; a=c=1; b=2; x=100; printf("\nf(2) = %ld",f(a,b,c,x)); getch(); } long f(int a,int b,int c,int x) { long z=a*x*x + b*x + c; return z; }

Ch : Cc hm c th nh ngha trc hm main(), xem cch 2. Nu cc hm nh ngha sau hm main() th phi khai bo tn hm v danh sch kiu i trc hm main(), nh cch 1 ni trn. Cch 2: S dng bin ngoi.
#include <stdio.h> #include <conio.h> int a,b,c,x; long p; long f() { long z=a*x*x + b*x + c; return z; }

void main(){ a=c=1; b=2; x=100; printf("\nf(2) = %ld",f()); getch(); }

3. Bin v mng t ng
- nh ngha: Bin, mng khai bo bn trong thn hm hoc i ca hm gi l bin mng t ng. - Phm vi hot ng: Bin, mng t ng ch c tc dng trong bn thn hm, k c vic cp pht b nh.

4. Bin v mng ngoi v t kho extern


+ nh ngha: Bin, mng khai bo bn ngoi cc hm gi l bin, mng ngoi . + Phm vi hot ng: Bin, mng ngoi ch c tc dng cho n cui tp chng trnh hin ti. Mun bin, mng ngoi c tc dng trong nhiu file th tin khai bo l extern. V d: Ta c tp MyLib.C, ni dung nh sau:
int x=10; long f(int n) {int i; long t=1; for(i=1;i<n;i++) t=t*i; return t; }

Ch : - File Mylib.C phi t trong th mc INCLUDE - File ny khng th thc hin v khng c hm main(), do ch c th dch sang file MyLib.OBJ, t menu Compile \ Compile to OBJ By gi ta s vit chng trnh USEMyLib.C , s dng cc bin v hm trong Mylib.C. File chng trnh ny c ni dung nh sau:
#include <stdio.h> #include <conio.h>

#include <ham3.c> extern int; extern long f(int); void main(){ printf("\n%d",x); printf("\n%ld",f(20)); getch(); }

Lu l cc tin t extern c th khai bo trong tp th vin ring. + V vic khi u cho cc bin , mng ngoi: . Cc bin, mng ngoi c th khi u mt ln. . Cc mng khi khi u c th khng cn ch ra kch thc. V d float a[] = { 2.5, 7.0, 8.5 } int b[][4] = { {2,6,14,7}, {0,0,3,45} } . Khi khi u cho cc mng kiu k t, c th khi u bng mt danh sch cc k t hoc xu k t. V d: char name[] = { h,a,32,n,o,i,\0} char name[] =ha noi * Ch k, kch thc ca mt bin, mng c tnh nh hm sizeof()

5. Bin tnh v mng tnh.


- Khai bo: dng tin khai bo static, - C th khi u mt ln. - Vn c cp pht b nh. - Phm vi hot ng: Ch hot ng trong thn hm m ti n c khai bo. Gi tr ca chng c gi li khi ra khi hm v khi hm hot ng tr li th gi tr c c tip tc s dng. V d:
#include <stdio.h> #include <conio.h> void f(){ static int x=9; x+=10; printf("\n%d",x);

} void main(){ int x=1; f(); printf("\n%d",x); f(); getch(); }

Kt qu khi chy chng trnh l 19 1 29 Khi b tin khai bo static trong hm f() th kt qu l 19 1 19

Bi 4. VO V RA

1. Hm printf v hm scanf
1.1. Hm printf int printf(const char *dng_iu_khin, danh_sch_i); - Hm tr li -1 khi c li. Khi khng li, hm tr li gi tr l s lng k t c in ra. - Dng iu khin bao gm: . Cc k t iu khin . Cc k t c t . Cc k t bnh thng - Cc k t iu khin bao gm : \n \t \r \b \f sang dng mi sang 1 tab CR: v u dng back space LF: line feed \0 \ \ \\ NULL du du du \

- Cc k t c t c dng tng qut: %[-][_rng][phn_thp_phn_i_vi_float]k_t_chuyn_dng Du tr quy nh kt qu in ra canh bin tri (mc nh l canh bin phi) stt K t Kiu chuyn dng d liu char int long int int long int k t s nguyn thng h 10, c th c du s nguyn di h 10, c th c du s nguyn h 10, khng du s nguyn h 8 khng du ( u khng c s 0) s nguyn di, h 8, khng du s nguyn h 16, khng du Cch chuyn dng

1. c 2. d 3. ld 4. u 5. o 6. lo 7. x

8. lx

long

s nguyn di h 16 khng du.

1.2. Hm scanf int scanf(const char *dng_iu_khin, danh_sch_a_ch_i); V d 1 int n; float r; scanf(%d%f,&n,&r); V d 2 int n; float x,y; char s[6], st[6]; scanf(%f%5f%3d%3s%s,&x,&y,&n,s,st); nu nhp dng vo l: 54.32e-1 25 12345678a Kt qu l: x==5.432 y==25.0 n=123 s=456 bao gm c k t \0 st=78a bao gm c k t \0

2. So snh 2 nhm hm trong stdio v conio


<stdio.h> : th vin dng vo v ra ca stdio, gm stdi v stdo - dng vo stdi gm scanf, gets, getchar (1) - dng ra stdo gm printf, puts, putchar (2) <conio.h> : th vin dng vo/ra trn mn hnh v bn phm gm : getch, getche, putch, putche, kbhit, clrscr, gotoxy (3)

2.1. Dng vo stdi v hm scanf - stdi l dng vo chun - tc l bn phm - Nu trn stdi cha d liu th scanf yu cu nhp cho n khi d liu. - Nu trn stdi d liu th nhm hm (1) s nhn mt phn d liu tng ng vi yu cu ca chng. Phn d liu cn li vn cn trn stdi. - Hn na, phn d liu cn li s t ng gn cho bin c nhp bi scanf (nu c lnh scanf tip theo) v khng c yu cu cn thc hin lnh scanf . Tuy nhin nu phn d liu cn li vn cha d liu cho cc bin tip theo th yu cu nhp i vi cc bin vn c nu ra. V d 1
#include <stdio.h> void main(){ int a,b,c; printf("\n a,b = "); scanf("%d%d",&a,&b); printf("\n a=%d, b=%d",a,b); printf("\n c = "); scanf("%d",&c); printf("\n a=%d, b=%d, c=%d",a,b,c); getch(); }

. Nu ta nhp a, b = 10 20 th vn xut hin yu cu nhp c, tc l kt qu thc hin l: a=10, b=20 c= 30 a=10, b=20, c=30 . Nu ta nhp a,b = 10 20 30 40 th khng c yu cu nhp c, tc l kt qu thc hin l: a=10, b=20 c= a=10, b=20, c= 30 gi tr 40 vn cn li trn stdi.

V d 2
#include <stdio.h> void main(){ int a,b,c,d; printf("\n a,b = "); scanf("%d%d",&a,&b); printf("\n a=%d, b=%d",a,b); printf("\n c,d = "); scanf("%d%d",&c,&d); printf("\n a=%d, b=%d, c=%d, d=%d",a,b,c,d); getch(); }

. Theo di kt qu khi chy chng trnh thy: a,b = 2 3 4 a=2, b=3 c,d = 5 6 a=2, b=3, c=4, d=5 V gi tr 6 b b qua, vn cn li trn stdi 2.2. Dng vo stdi vi cc hm gets v getchar - Khi nhp xu k t s, t khi dng hm scanf v hm scanf khng c kh nng nhp xu k t cha du cch. Ni cch khc phm space cng l kt thc nhp mt xu k t (i vi scanf). V d 1 char s[25]; scanf(%s,s); printf(s=%s,s) nu nhp thu ha kt qu l s=thu - Trong trng hp ny ta s dng gets thay cho scanf V d 2 char s[25]; gets(%s,s); printf(s=%s,s) nu nhp le thu ha

kt qu l s=le thu ha - Hm gets(s) nhp mt xu k t cho bin s ; hm puts(s) in ra xu k t trong bin s. - Tng qut, hm gets c c php: char *gets(char *s) s l bin con tr kiu char tr v a ch vng nh chau k t nhn c. Hm gets nhn mt dy k t stdi cho n khi nhn , tc l n khi nhn c k t \n th gets dng li v \n nm li trn stdi. Nh vy, thay v t k t \n vo cui xu k t s th hm gets t k t \0 (k t null) vo cui xu nh du kt thc xu. Ch rng hm gets khng tr v gi tr xu k t m tr v a ch ca xu k t . - Hm getchar(void) c c php tng qut nh sau: int getchar(void) c tc dng nhp mt k t t bn phm. V d char c, kt; kt=getchar(); . Nu nhp A th kt = A , k t \n vn nm li trn stdi . Nu nhp th kt =\n v trn \n b loi khi stdi. - Hm putchar() a mt k t ra stdo chun - mn hnh. 2.3. Hin tng tri d liu (nh hng ca scanf v getchar i vi gets) - Nh trn suy ra , hm gets dng li khi trn stdi c k t \n (CR) - T , cc hm scanf v getchar c th lm cho hm gets mt tc dng. Ngha l mc d trong chng trnh c vit lnh gets nhng khi chy chng trnh th lnh ny khng c thc hin. Hin tng ny gi l hin tng tri d liu. V d 1
#include <stdio.h> void main(){ int tuoi; char hoten[25]; printf("\n tuoi: "); scanf("%d,&tuoi); printf("\n ho ten: "); getsf(hoten);

printf("\n tuoi: %d, ho ten: %s",tuoi,hoten); getch(); }

. Nu ta nhp 45 th kt qu l tuoi:45, ho ten: ngha l vic nhp gi tr cho bin hoten khng c tc dng. . Nu ta nhp 45 nguyen thanh thuy th kt qu l tuoi:45, ho ten: nguyen thanh thuy - Ni chung nhp d liu cho ng ta nn s dng lnh lm sch stdi , v khi trn stdi khng cn k t \n , do khng b tri cc hm nhp d liu khc, nh hm gets. Hm fflush(stdi); s lm sch stdi V d 2
#include <stdio.h> void main(){ int tuoi; char hoten[25]; printf("\n tuoi: "); scanf("%d,&tuoi); printf("\n ho ten: "); fflush(stdi); getsf(hoten); printf("\n tuoi: %d, ho ten: %s",tuoi,hoten); getch(); }

2.4. Dng ra stdo vi nhm hm 2 - Th vin conio.h cha cc hm kiu int sau y: . getch() : nhn mt k t t b m bn phm, khng hin ln mn hnh . getche(): nhn mt k t t b m bn phm, c hin ln mn hnh . putch(): a mt k t ln mn hnh vn bn, c mu sc quy nh bi hm textcolor(), trong khi , hm putchar() lun hin ln mu trng. . kbhit(): Cho bit trong b m bn phm c cn k t no khng. kbhit()=0 (tc FALSE) khi b m bn phm rng

kbhit()=1 (tc TRUE) khi b m bn phm c cc k t Ch : - Nu g phm trong khi my dng ch kt thc nhp d liu bi cc hm scanf, gets, getchar th cc k t s gi vo stdi - Nu g phm trong cc trng hp khc, v d i vi hm getch, getche th cc k t s gi vo b m bn phm. V d 1 (chy trong mode MS-DOS) Lp qu trnh nhp mt s k t vo b m b m bn phm n khi nhp k t 27. Ly cc k t t b m bn phm nhp in ln mn hnh:
#include <stdio.h> #include <conio.h> void main(){ int c; clrscr(); while (getch()!=27) putch(7); while(kbhit()) { c=getch(); putch(c); } }

Chng 2. CC TON T IU KHIN


Bi 1. TON T R NHNH IF V CHUYN SWITCH

1. Ton t r nhnh if
- Dng khuyt: if(biu_thc) { nhm_lnh; } - Dng : if(biu_thc) { nhm_lnh_1; } else { nhm_lnh_2;} - Cc v d : V d 1 : Gii phng trnh bc hai: ax2 + bx + c (a<>0)
#include <stdio.h> #include <conio.h> #include <math.h> main() { float a,b,c,d,x1,x2; printf("\n nhap a,b,c: "); scanf("%f%f%f",&a,&b,&c); d=b*b-4*a*c; if(d<=0) printf("\n phuong trinh vo nghiem"); else if(d==0) printf("\n phuong trinh co nghiem kep %10.2f",b/(2*a)); else { x1=(-b+sqrt(d))/(2*a); x2=(-b-sqrt(d))/(2*a); printf("\n phuong trinh co 2 nghiem phan biet:"); printf("\n x1= %10.2f\n x2= %10.2f",x1,x2); } getch(); }

V d 2 : Nhp t bn phm im trung bnh mn ca mt sinh vin, in ln mn hnh xp loi hc lc sinh vin . . Di 5.0 : xp loi yu . T 5.0 n di 6.5: xp loi trung bnh . T 6.5 n di 8.0: xp loi kh . T 8.0 tr ln : xp loi gii

#include <stdio.h> #include <conio.h> main() { float dtb; char *xl; printf("\n nhap diem trung binh: "); scanf("%f",&dtb); if(dtb<5.0) xl="YEU"; else if(dtb<6.5) xl="TRUNG BINH"; else if(dtb<8.0) xl="KHA"; else xl="GIOI"; printf("\n xep loai sinh vien do la %s",xl); getch(); }

V d 3: Nhp t bn phm mc lng ca 4 cn b nhn vin. In ln mn hnh mc lng cao nht ? thp nht.
#include <stdio.h> #include <conio.h> main() { float a,b,c,d,max,min; printf("\n nhap muc luong cua 4 nhan vien: "); scanf("%f%f%f%f",&a,&b,&c,&d); max=a>b?a:b; if(max<c) max=c; if(max<d) max=d; min=a>b?b:a; if(min>c) max=c; if(min>d) max=d; printf("\n luong cao nhat la %0.1f\n luong thap nhat la %0.1f", max,min); getch(); }

2. Ton t chuyn switch


- C php tng qut: switch(biu_thc_nguyn){ case 1: nhm_lnh_1; case 2: nhm_lnh_2; ... case n: nhm_lnh_n; [default : nhm_lnh_mc_nh; ] } - Hot ng ca ton t switch: + Khi biu thc c gi tr k (k<=n) th bt u t lnh c nhn k c thc hin. Cc lnh c nhn bn di vn tip tc c thc hin nu nh trc khng c lnh ngt, y l im lu v n khc bit so vi cu trc case ca pascal. Vy swith khng c hiu l thay th cu trc if .. else lng nhau. + Khi biu thc khng c gi tr no trong on [1..k] th nhm lnh phn default c thc hin (nu c) hoc ra ngay khi swith (nu khng c default) + Tng qut, ton t swith kt thc trong cc trng hp sau y: . Thc hin xong phn default nu c hoc gp du } cui cng ca khi switch . Gp cu lnh ngt break. T nu sau mi trng hp ca swith c mt cu lnh break th ch mt trong cc trng c thc hin v sau ra khi switch, lc ny switch s ging vi cu trc case ca pascal. . Gp cu lnh nhy goto ra mt nhn ngoi swith * Ni chung bin lun cc trng hp cho mt bi ton, ta nn thm mt cu lnh ngt break sau mi trng hp ca swith - Cc v d V d 1
#include <stdio.h> main() {

int i; printf("\n i= "); scanf("%d",&i); switch (i) { case 1 : printf("\n lenh 1"); case 2 : printf("\n lenh 2"); case 3 : printf("\n lenh 3"); case 4 : printf("\n lenh 4"); default : printf("\n lenh default"); } getch(); }

Nu ta nhp i=1 th kt qu l lenh 1 lenh 2 lenh 3 lenh 4 lenh default Nu ta nhp i=3 th kt qu l lenh 3 lenh 4 lenh default * T bin i ch c tc dng quyt nh bt u t lnh no c thc hin. Cc gi tr nhn bn di (cho d khc i) vn c thc hin, khng ph thuc vo gi tr ca i na !. V d 2
#include <stdio.h> #include <conio.h> main() { int i; printf("\n i= "); scanf("%d",&i); switch (i) { case 1 : printf("\n%d",i); i+=4; case 3 : printf("\n%d",i); i+=2; case 5 : printf("\n%d",i); i+=9; case 14 : printf("\n%d",i); i+=2; default : printf("\n%d",i); i=100; }

printf("\n%d",i); getch(); }

Nu ta nhp i = 1, kt qu l Kt qu 1 5 7 16 18 100 Gii thch i=1, lnh nhn 1 thc hin, in ra i=1 v i=5 lnh nhn 3 thc hin, in ra 5 v i=7 lnh nhn 5 thc hin, in ra 7 v i=16 lnh nhn 14 thc hin, in ra 16 v i=18 lnh default thc hin, in ra 18 v i=100 lnh sau switch thc hin, in ra 100

Nh vy, sau khi lnh nhn 1 thc hin, i = 5. Nhng khng phi v th m swith s nhy ti nhn 5. Nhn 3 ngay sau vn c thc hin. Nh vy, mt ln na chng t gi tr ca i ch c tc dng quyt nh lnh no c thc hin u tin. Cc nhn sau khng lin quan g n bin i. Nu ta nhp i = 3 kt qu l: 3 5 14 16 100 V d 3 Mt thng c 26 ngy cng. Mt cng nhn c th lm thm 1 hoc 2 hoc 3 hoc 4 ngy na. S tin thng quy nh nh sau: Nu s ngy lm thm l: 1: thng 30.000 2: thng 100.000 3: thng 150.000 4: thng 210.000 Lng gc ca mt cng nhn l 350.000 ng.

Hy vit chng trnh tnh tng lng ca mt cng nhn khi bit s ngy lm thm ca h.
#include <stdio.h> #include <conio.h> main() { int sn,thuong; printf("\n so ngay lam them = "); scanf("%d",&sn); switch (sn) { case 1 : thuong=30; break; case 2 : thuong=100; break; case 3 : thuong=150; break; case 4 : thuong=210; break; default : thuong=0; } printf("\n tong luong la %ld dong",1000*((long)thuong+310)); getch(); }

Ch : ta phi chuyn bin thuong kiu int thnh kiu long thng qua php chuyn l (long)thuong trc khi thc hin php nhn vi 1000. V nu khng kt qu php tnh cc bin nguyn s cho gi tr nguyn, b trn s. V d 4 Mt my M gm 5 van k1, k2, k3, k4,k5 nh m t hnh v:

k1

k2

k3

k4

k5

1 Trng thi 1

0 Trng thi 2

My M gm 5 van

Cc van quy c 2 trng thi

Mt trng thi ca my l mt dy 5 trng thi ca 5 van. Theo hnh v, trng thi ca my l (10011). Mi trng thi ca my c tc dng iu khin mt b phn no trong mt h thng tng th m ta khng ni ti y. My ny c 2 nt iu khin A v B v hot ng nh sau: nu nt A c nhn th mt qu cu s ln vo ng ng A v chy qua cc ng trong my cui cng thot ra mt trong 4 ng ng bn di theo nguyn tc: . Ch i qua ng khng b van no ngn li . Khi i qua mt van th lm cho van i trng thi ngc li. My hot ng hon ton tng t khi nhn nt B. Chng hn nu ta nhn nt A th t trng thi (10011) s bin thnh trng thi (00111); nhn tip nt B, s bin thnh trng thi (01110),... Yu cu: Gi (k1,k2,k3,k4,k5) l trng thi xut pht ca my, hy xc nh trng thi mi ca my sau khi nhn mt nt no . Chng trnh:
#include <stdio.h> #include <conio.h> main() { int k1,k2,k3,k4,k5; char nut; int next; printf("\n nhap day trang thai cua 5 van : "); scanf("%d%d%d%d%d",&k1,&k2,&k3,&k4,&k5); fflush(stdin); printf("\n nhan nut A hay nut B: "); nut=getchar(); printf("\n ban dau: %d%d%d%d%d",k1,k2,k3,k4,k5); switch (nut) { case 'A' : if(k1) next=3; k1=!k1; case 34 : if(next==3) k3=!k3; else k4=!k4; break; case 'B' : if(k2) next=4; k2=!k2; case 45 : if(next==4) k4=!k4; else k5=!k5; } printf("\n sau nhan: %d%d%d%d%d",k1,k2,k3,k4,k5); getch(); }

Lu : Cc nhn 34, 45 ch gi lp, khng c ngha g i vi bin lun ca bin nut.

Bi 2. CC TON T LP FOR V WHILE

1. Ton t lp for
- C php for(biu_thc1;biu_thc2;biu_thc3) { nhm_lnh; } - Hot ng ca ton t (lp) for: Bc 1: Tnh gi tr biu thc 1 Bc 2: Nu biu thc 2 sai th thc hin Bc 5 (kt thc) Bc 3: /* ngm hiu biu thc 2 ng */ - Thc hin Nhm_lnh. - Tnh gi tr biu thc 3. Bc 4: Quay v Bc 2. Bc 5: Kt thc. - Ch : . Trong for gm 3 thnh phn biu_thc1, biu_thc2, biu_thc3. Cc thnh phn ny ngn cch bi du chm phy ( ; ). . Trong tng thnh phn c th cha nhiu biu thc con v cc biu thc con trong mt thnh phn ngn cch bi du phy ( , ). . Cc biu thc 1,2,3 trong for c th vng mt. . Khi biu thc 2 vng mt th ngm nh lun ng. Khi , vng lp for s kt thc khi gp mt trong cc lnh break / goto/ return. Nu vng mt biu_thc2 th gia biu_thc 1 v biu_thc2 phi c 2 du chm phy. . Biu thc 1 gm nhng lnh khi u cho bin iu khin vng lp v cc bin cn phi tnh ton, do vy c th khi u trc for v khi khuyt biu thc 1. . Trong bc 3 gm 2 vic : thc hin nhm lnh (thn vng lp for ) v tnh gi tr biu thc 3. Vy c th cho cc lnh tnh gi tr biu thc 3 gp chung vi nhm lnh. Trong trng hp ny biu thc 3 s vng mt. Ngc li, cng c th gp chung nhm lnh (nht l khi t lnh) vi biu thc 3, khi thn vng for l rng! . Trong c 2 cch gp chung nh trn, th t vit nhm lnh trc hay biu thc 3 trc l kh quan trng , n nh hng n vic tng hay gim mt bc lp trong

vng lp for, do c th phi iu chnh li cc lnh trong biu thc 2 mt cch hp l. . Trong thn vng lp for {...} nu gp lnh continue th cc lnh cn li c b qua v chuyn n xt biu thc 3. - V d : Vit chng trnh o ngc dy s thc cha trong mng x. float x[] = {6.3, -4.7, 70.2, 14.5 , -22.1} int n = sizeof(x) / sizeof(float); void main() { int i,j; float c; ( ) getch(); } Trong ( ) gm cc cch sau y: Cch 1 ( ) cc thnh phn v thn for for(i=0,j=n-1 ; i<j ; i++, j--) { c=x[i]; x[i] =x[j]; x[j]=c;} Cch 2 ( ) Khuyt thn for: for(i=0,j=n-1 ; i<j ; c=x[i], x[i] =x[j], x[j]=c, i++, j--); Cch 3 ( ) Khuyt biu thc 1 i=0; j=n-1; for( ; i<j ; i++,j--) {c=x[i]; x[i] =x[j]; x[j]=c;} Cch 4 ( ) Khuyt biu thc 2 for(i=0, j=n-1; ; i++, j--) {c=x[i]; x[i] =x[j]; x[j]=c; if (i>j) break;} Cch 5 ( ) Khuyt biu thc 3 for(i=0, j=n-1; i<j ;) {c=x[i]; x[i] =x[j]; x[j]=c; i++; j--;} Cch 6 ( ) Khuyt c 3 biu thc i=0; j=n-1; for(;;) {c=x[i]; x[i] =x[j]; x[j]=c; if(i++> j--) break;}

Cn nhiu cch khc i=0; j=n-1; for(;i<j;){c=x[i]; x[i] =x[j]; x[j]=c; i++; j--;} Hoc : for(i=0, j=n-1;;) {c=x[i]; x[i] =x[j]; x[j]=c; if(i++> j--) goto next;} next: Mt s bi tp v ton t (lp) for Bi 1 Vit chng trnh tnh an vi a>0, n>0
#include <stdio.h> void main() { int a,n,i; long t=1; printf("\n nhap a,n : "); scanf("%d%d",&a,&n); for(i=1;i<=n;t*=a,i++); printf("\n %d^%d = %ld",a,n,t); getch(); }

Bi 2 Vit chng trnh tnh an vi a<>0, n<>0


#include <stdio.h> void main() { int a,n,b,m,i; float t=1; printf("\n nhap a,n : "); scanf("%d%d",&a,&n); b=abs(a); m=abs(n); for(i=1;i<=m;t*=b,i++); if(n<0) t=1/t; if(a<0 && (n%2!=0)) t=-t; printf("\n %d^%d = %0.2f",a,n,t); getch(); }

Bi 3 Vit chng trnh tnh n! vi s n nguyn dng nhp t bn phm .


#include <stdio.h> void main() {

int n,i; long t=1; printf("\n nhap n : "); scanf("%d",&n); for(i=1;i<=n;t*=i,i++); printf("\n %d! =%ld",n,t); getch(); }

Bi 4 Vit chng trnh tm tt c cc s nguyn trong khong 1000 n 9999 tha mn s bng tng ca trng phng ca 4 ch s ca n. (kt qu c 2 s : 1634, 8208)
#include <stdio.h> long f(int x) {return (long)x*x*x*x; } void main() { int a,b,c,d; for(a=1;a<9;a++) for(b=0;b<9;b++) for(c=0;c<9;c++) for(d=0;d<9;d++) if((long)(a*1000+b*100+c*10+d)==f(a)+f(b)+f(c)+f(d)) printf("\n%d%d%d%d",a,b,c,d); getch();}

Bi 5 : Lp trnh in ln mn hnh cc hnh sau y Hnh 1 1 12 123 1234 123456 123456 12345 1234 123 12 Hnh 2 1 121 12321 1234321 123454321 12345654321 Hnh 3 1 232 34543 4567654 567898765 67890109876 7890123210987 890123454321098 90123456765432109 0123456789876543210

HINH1.C
#include <stdio.h> void main() { int line,i; clrscr(); for(line=1;line<=6;line++) {for(i=1;i<=line;i++) printf("%d",i); printf("\n"); } printf("\n"); for(line=6;line>=1;line--) {for(i=1;i<=line;i++) printf("%d",i); printf("\n"); } getch();}

HINH2.C
#include <stdio.h> void main() { int line,i,j,k=5; clrscr(); for(line=1;line<=6;line++) {for(j=1;j<=k;j++) printf("%c",32);k--; for(i=1;i<=line;i++) printf("%d",i); for(i=line-1;i>=1;i--) printf("%d",i); printf("\n"); } getch();}

HINH3.C
#include <stdio.h> void main() { int line,i,j,k=10; clrscr(); for(line=1;line<=10;line++) { for(j=1;j<=k;j++) printf("%c",32);k--; j=line; for(i=1;i<=line;i++) {if(j<10) printf("%d",j);else printf("%d",j%10); j++;}

j-=2; for(i=line-1;i>=1;i--) {if(j<10) printf("%d",j);else printf("%d",j%10); j--;} printf("\n"); } getch(); }

Bi 6 Tm tt c cc s nguyn t trong on [a,b]; a<b l cc s nguyn nhp t bn phm.


#include <stdio.h> #include <conio.h> main() { int a,b; int d,i,k; do{ printf("\n nhap cac gia tri a,b: "); scanf("%d%d",&a,&b); } while ( (a<=0)||(a>=b)); for(k=a;k<b;k++) {for(d=0,i=1;i<=k/2;i++) if(k%i==0) d++; if(d==1) printf("\t%d",k); } getch(); }

Bi 7 Tm tt c cc s hon thin trong on [a,b]; a<b l cc s nguyn nhp t bn phm.


#include <stdio.h> #include <conio.h> main() { int a,b; int d,i,k; do{ printf("\n nhap cac gia tri a,b: "); scanf("%d%d",&a,&b); } while ( (a<=0)||(a>=b)); for(k=a;k<b;k++) {d=0; for(i=1;i<=k/2;i++) if(k%i==0) d+=i; if(d==k) printf("\t%d",k); } printf("\n xong !");

getch(); }

2. Ton t while
- C php: c 2 dng Dng 1 while(biu_thc) { nhm_lnh;} Dng 2 do { nhm_lnh } while (biu_thc); + Ging nhau, nhm lnh lp cn thc hin khi biu thc cn ng (biuthc == 1) + Khc nhau, dng 1 kim tra iu kin trc cn dng 2 kim tra iu kin sau. V vy, do while cho php nhm lnh lp thc hin t nht mt ln. V d 1 Vit on chng trnh nhp s nguyn n > 0. - Dng do while do { printf(\n nhap n:); scanf(%n,&n); } while(n<=0); - Dng while printf(\n nhap n:); scanf(%n,&n); while(n<=0) { printf(\n nhap n:); scanf(%n,&n);} hoc while(1) { printf(\n nhap n:); scanf(%n,&n); if(n>0) break;} Mt s bi tp v ton t (lp) while Bi 1

Vit 2 chng trnh vi 2 cch khc nhau tm USCLN ca 2 s nguyn dng a,b nhp t bn phm. Phng php tr lin tip
#include <stdio.h> #include <conio.h> main() { int a,b,a1,b1; printf("\n nhap 2 so a,b :"); scanf("%d%d",&a,&b); a1=a;b1=b; while(a!=b) if(a>b) a-=b; else b-=a; printf("uscln(%d,%d)=%d",a1,b1,b); getch(); }

Phng php chia lin tip


#include <stdio.h> #include <conio.h> main() { int a,b,a1,b1,r; printf("\n nhap 2 so a,b :"); scanf("%d%d",&a,&b); a1=a;b1=b; while((r=a%b)!=0) {a=b;b=r;} printf("uscln(%d,%d)=%d",a1,b1,b); getch(); }

Bi 2 Vit chng trnh tnh gi tr gn ng y = ex , bit hm ny c th khai trin di dng chui Taylor nh sau: ex = 1+x/1! + x2/2! + ... + xi /i! + ... vi i khng vt qu N hoc vi chnh xc E = 0.001 , tc l | xi /i! | < E
#include <stdio.h> #include <conio.h> #define Epxilon 0.001 #define N 100 long gt(int n) {long t; int i; for(t=1,i=1;i<=n;t*=i,i++); return t; }

float Ex(float x) { float E=1.0; int i=1; while( ( x/gt(i)>Epxilon) && (i<N) ) {E+=x/gt(i); i++;} return E; } void main() { float x; printf("\n x= "); scanf("%f",&x); printf("\n E(%0.2f)= %0.3f",x,Ex(x)); getch(); }

Bi 2 Vit chng trnh tnh gi tr cc hm sin(x) v cos(x) theo khai trin Taylor nh sau: (vi i khng vt qu N hoc vi chnh xc E = 0.001.) sin(x) = x - x3/3! + x5/5! - ... + (-1)i x(2i+1)/(2i+1)! cos(x) = 1 - x2/2! + x4/4! - .... + (-1)i x2i/(2i)! Sincos.C
#include <stdio.h> #include <conio.h> #define Epxilon 0.0001 #define N 100 long gt(int n) {long t; int i; for(t=1,i=1;i<=n;t*=i,i++); return t;} float mu(float a,int n) {float t; int i; for(t=1.0,i=1;i<=n;t*=a,i++); return t;} float sin(float x) { float k,S=x; int i=3,d=-1; while ( (i<N) && ( (k=mu(x,i)/gt(i)) > Epxilon) ) {S+=d*k; i+=2; d=-d;} return S; } float cos(float x)

{ float k,S=1; int i=2,d=-1; while ( (i<N) && ( (k=mu(x,i)/gt(i)) > Epxilon) ) {S+=d*k; i+=2; d=-d;} return S;} void main() { float x; printf("\n x= "); scanf("%f",&x); printf("\n sin(%0.2f)= %0.9f",x,sin(x)); printf("\n cos(%0.2f)= %0.9f",x,cos(x)); getch(); }

Chng 3. CON TR V MNG


Bi 1. BIN CON TR

1. Tc dng ca bin con tr


Bin con tr c 2 tc dng: - Dng cha a ch ca bin. - Xin cp pht b nh ng. Mc ch ca vic cha a ch ca bin l truyn a ch ca i cho hm, v ni chung l trc tip lm vic vi a ch ca bin, chng hn nh cc xu k t. Mc ch ca vic cp pht b nh ng l ti u ha vic s dng b nh cho cc bin trong chng trnh hoc tnh n vic t chc tt d liu ph hp vi mt nh (thut ton) no .

2. Khai bo bin con tr


Kiu_d_liu *tn_bin_con_tr; V d int *x; float *r; long *l; unsigned long *w; char *name; Bin con tr cng phi c kiu d liu v c kiu d liu trng vi kiu d liu ca bin m n cha a ch. Trong trng hp cp pht b nh cho cc bin ng th bin con tr c kiu d liu trng vi kiu d liu ca cc bin ng . V d Nu ta c bin nguyn x v mt bin con tr px cha a ch ca x th ta c khai bo: int x; int *px; v c lnh px=&x;

3. S dng bin con tr khi bin con tr cha a ch ca bin


Gi s ta c khai bo dng (1) int x; int *px; px=&x; Khi vit px l ch &x, tc l px==&x vit *px l ch x , tc l *px ==x

Nh vy sau khai bo dng (1) (cch 2): int x; int *px = &x; Sau lnh: *px = 10; th x ==10; x=20; th *px=20; Cc lnh sau y sai: px=x; sai v px l bin con tr, khng cha c gi tr ca bin x x==px; sai v gi tr ca x khng bng a ch ca n lu trong px Nhng quy tc ny c ghi nh vn dng khi truyn i cho hm kiu con tr v ni chung trong cc vn m ta lm vic gin tip vi bin thng qua con tr cha a ch ca bin . V d
#include <stdio.h> #include <conio.h> void main(){ int x; int *px; px=&x; printf(\n nhap x: ); scanf(%d,px); printf(\n x=%d, x); x+=10; printf(\n x=%d, *px); *px+=11; printf(\n x=%d, x); getch();

4. Bin con tr v hng a ch


4.1. V php ton i vi bin con tr Nu c khai bo dng (1): int x, *px=&x; Th : - Tt c cc php ton p dng c cho x cng p dng c cho *px - &x th khng c php ton no. - px th c cc php ton tng, gim a ch. C ngha l mc d px==&x Nhng lnh px++ ; l ng (1) Cn lnh (&x)++; l sai. (2) - Lnh (2) sai v a ch ca bin x l mt a ch vt l ca b nh c cp pht v c nh ngay t lc dch chng trnh. Nh vy, a ch ca bin l mt hng a ch, khng c php thay i trong chng trnh. - Lnh (1) ng v px hon ton c lp vi x, n c kh nng khng nhng ch vo a ch ca x m cn c th tr vo cc a ch khc (trong trng hp ny l cc a ch kiu int, 2B). Trc khi thc hin lnh (1) con tr px tr vo a ch ca x, sau lnh (1) th px s tr vo a ch ca vng nh l 2 byte tip theo, ngay sau 2 Byte a ch ca x. Khi px l con tr kiu nguyn th sau mi mt ln lnh tng a ch thc hin, px s ch vo 2 Byte tip theo trong b nh. Tng t nh th , nu px l con tr kiu long , px s chi vo cc a ch 4 Bte; nu px kiu float, n s ch vo cc a ch 6 Byte. 4.2. Phn bit hng a ch vi bin con tr trong trng hp xu k t Mt xu k t c th c 2 cch khai bo, hay ni mt cch chnh xc l 2 cch biu din: - S dng mt mng cc k t char name[30]; (cch 1) - S dng mt con tr kiu char char *pname; (cch 2) Vn l khi no s dng cch no, phn bit 2 cch khc nhau nh th no? (a) Trc ht , v cch s dng con tr kiu char

Nu ta c char *name; th php gn : name=le thu ha ngha l gn con tr name bng a ch ca hng xu k t le thu ha, do , 2 lnh sau c tc dng ging nhau cho hin ln mn hnh dng ch le thu ha: puts(le thu ha); v puts(name); (b) Phn bit cch dng mng kiu char v con tr kiu char. V d 1: ng char *name, s[30]; name=le thu ha; gets(s); V d 2: Sai char *name, s[30]; (1) s=le thu ha; (2) gets(name); (3)

V d 1 ng nh gii thch trong mc (a). V d 2 sai: - Cu lnh (2) sai v s l mt mng kiu char m l mng th tn mng l mt hng a ch, do v tri l mt hng a ch, v phi l mt hng a ch khc, vy, khng th gn hng a ch ny bng mt hng a ch khc c. - Cu lnh (3) khng sai v mt c php, nhng trong trng hp ny l v ngha. Bi v name l mt con tr (kiu char) cho nn n phi tr vo mt a ch (kiu char) no . Chng hn, nu name tr vo a ch ca s , tc l nu c lnh: char *name, s[30]; name=s; (cng ging nh lnh px = &x) th 2 lnh sau y l c tc dng nh nhau: gets(name); gets(s);

5. S dng con tr xin cp pht b nh ng


- Trong mc 3 v 4 trnh by v nguyn tc s dng con tr cha a ch ca bin v phn bit gia con tr v hng a ch (ca bin). Trong mc 5 ny s nghin cu v cch s dng bin con tr xin cp pht b nh ng.

5.1. Cp pht v gii phng b nh cho bin ng - Trong C, hm malloc cp pht b nh ng. - Xt mt bin con tr px c kiu T no : T *px; - Gi s kiu T chim k byte, tc k=sizeof(T). - cp pht k byte cho mt bin ng kiu T ta dng lnh: px = (T*) malloc (sizeof(T)); V d V d 1: v ngha int *px; *px=10; V d 2: c ngha int x,*px=&x; *px=10; V d 3: c ngha int *px; px = (int*) malloc (sizeof(int)); *px=10;

V d 1 khng sai v mt c php lnh nhng v ngha v con tr px khng r ang ch vo a ch no. Gi thit vi mt a ch vu v no m px ang tr vo th nh c a ch ny ny nhn ni dung l 10. Tri li, v d 2, px ang tr vo a ch ca x, do nh dnh cho x s nhn gi tr 10. Cn v d 3, mc d khng c bin tnh no, nhng mt bin ng (khng c tn - ng nhin) c to ra v cha gi tr 10. - cp pht n*k byte cho mt dy n bin ng kiu T ta dng lnh: px = (T*) malloc (n*sizeof(T)); Ta s xem xt dy bin ng ny trong mc 5.2 di y. - gii phng cho b nh cho bin ng (hoc dy bin ng) c qun l bi con tr px (tc l c cp pht nh px) ta dng hm free free(px); 5.2. Qun l dy bin ng Theo mc 5.1, dy n bin ng kiu T ( k byte) c cp pht v gii phng nh sau: px = (T*) malloc (n*sizeof(T)); v free(s); Khi dy bin ng ny c s dng nh mt mng mt chiu cc phn t kiu T. Cc vn v x l mng u a v vic duyt mng, v y l duyt dy n bin ng. Ta s s dng trit cc php tng, gim a ch i vi

con tr duyt trn dy n bin ng. Ni chung nn c thm mt con tr ph py no (kiu T) duyt trn dy bin ng, con tr px c gi nguyn xc nh a ch u ca dy n bin ng. duyt xui, ta cho py bt u t px v tng a ch con tr py n-1 ln n phn t th n ca dy; duy: duyt ngc, ta gim dn a ch con tr py n khi py chm vo px th dng li V d: Nhp dy n bin ng kiu nguyn, in dy ln mn hnh.
#include <stdio.h> #include <conio.h> main(){ int *px,*py; int n,i; printf("\n n= "); scanf("%d",&n); px = (int*) malloc (n*sizeof(int)); py=px; for(i=1;i<=n;i++) { printf("a[%d]= ",i); scanf("%d",py); py++; } printf("\n day n so da nhap la:"); py=px; for(i=1;i<=n;i++) { printf("%d ",*py); py++; } getch(); free(px); }

5.3. Con tr cp pht b nh cho xu k t Tng kt li nhng vn trnh by v xu k t , c bit l mc mc 4. Ta thy: (1) Nhm lnh sau y l bnh thng char s[30]; gets(s); puts(s); Nhng lnh sau l sai: s = le van binh (2) Nhm lnh sau y l bnh thng char *s; s=le van binh; puts(s);

Nhng lnh sau l v ngha: gets(s); (3) Trong trng hp (2), trng hp biu din xu k t bng con tr kiu char v mun nhp mt xu k t t bn phm m khng mun khi to mt hng xu k t ( nh (2) ), tc l lm cho lnh gets(s) c ngha, ta c 2 cch: Cch 1: Dng thm mt bin mng kiu char, ri cho con tr s tr vo hng a ch tg char *s, tg[30]; s=tg; gets(tg); hoc gets(s); Cch ny xem ra tr thnh tha bin ! Cch 2: Xin cp pht b nh ng cho n k t cha xu k t v dng con tr (kiu char) xc nh: char *s; int n = 30; s = (char*) malloc (n*sizeof(char)); V xu k t thc s th c k t \0 cui nn vi xu n k t s cn n+1 byte , v th nn vit l: char *s; int n = 30; s = (char*) malloc ((n+1)*sizeof(char)); V d
#include <stdio.h> #include <conio.h> main(){ char *s; int n=30; s= (char*) malloc (n*sizeof(char)); puts("nhap s: "); gets(s); printf("\n%s",s); { char x[30]; strcpy(x,s); printf("\n%s",x); } getch(); }

Khi lnh l lng c a vo l v ta mun khai bo thm mt bin gia chng main(). Nu khai bo ny khng c a vo khi lnh th s li.

Bi 2. TRUYN I CHO HM. CON TR TR TI HM


Ngoi vic hm s dng bin ton cc, hm cn c giao nhim v vi cc i (tham s) truyn cho hm. C s dng 2 cch truyn tham s cho hm trong C l truyn theo gi tr v truyn theo con tr. (C++ c thm mt cch mi truyn tham s cho hm l truyn tham s kiu tham chiu.)

1. Truyn tham s kiu gi tr cho hm


Theo cch truyn theo gi tr th ch c bn sao ca i c hm s dng. Trong thn hm, cc gi tr ny c th b thay i nhng ra khi hm th gi tr ban u ca i vn gi nguyn. ng nhin gi tr u vo ca i c gi nguyn v khng phi l chnh bn thn i truyn cho hm m l bn sao ca i c truyn cho hm. S thay i cc gi tr trong hm l ch thay i gi tr ca bn sao ca n m thi. V d 1 (thso1.cpp)
#include <stdio.h> #include <conio.h> void swap(int,int); main() { int x=10,y=5; clrscr(); swap(x,y); printf("x=%d y=%d\n",x,y); getch(); } void swap(int x,int y) {int z=x; x=y; y=z;}

Kt qu x = 10 y=5

2. Truyn tham s kiu con tr cho hm


Khi i truyn cho hm kiu con tr th lc gi hm cc con tr ny s thay th bng a ch ca cc bin truyn vo hm hoc l mt con tr hon ton xc nh ngha l ang cha mt a ch ca mt bin no . Nh vy v bn cht th bn gc ca i c truyn cho hm ch khng phi l bn sao ca n. V vy, nhng gi tr ca i b thn hm lm thay i s c gi li khi hm kt thc. V d 2 (thso2.cpp)

#include <stdio.h> #include <conio.h> void swap(int*,int*); main() { int x=10,y=5; clrscr(); swap(&x,&y); printf("x=%d y=%d\n",x,y); getch();}

Kt qu x = 5 y=10

void swap(int *x,int *y){int z=*x; *x=*y; *y=z;}

Ch - Khi khai bo: void swap(int*,int*) - Khi nh ngha: void swap(int *x,int *y) { // dng *x v *y; } - Khi s dng: swap(&x,&y)

3. Con tr tr ti hm
3.1. C php chung - Khai bo con tr ti hm (con tr tr ti hm) kiu_d_liu_ca_hm (*tn_con_tr_hm) (kiu_ca_cc_i) { thn_hm;} - S dng hm trong main() tn_con_tr_hm = tn_hm_no__cng_kiu_d_liu; V d 1: xt khai bo sau, c 2 con tr hm kiu float: float (*f)(float), (*mf[50])(int); . f l tn con tr hm (gi tt l con tr hm) kiu float gm mt i kiu float. . mf l mng con tr hm ( mng 50 phn t) cng c kiu float , c mt i kiu int. V d 2: xt khai bo sau , c 2 con tr hm cng c kiu double double (*g)(int,double), (*mg[30])(double,float); . g l con tr hm c kiu double, gm 2 i c kiu int v double . mg l mng con tr hm (30 phn t) kiu double, gm 2 i kiu double v float.

3.2. Tc dng ca con tr hm. i ca hm l con tr hm - Con tr hm dng cha a ch ca hm (kiu ca hm v kiu ca con tr hm phi ging nhau). Do , c th truyn i cho hm l mt con tr hm, tc l i ca mt hm c th l mt hm khc. - Khi khai bo i ca hm l con tr hm th ta vn khai bo con tr hm nh khai bo bn ngoi. - Khi s dng i (l con tr hm) trong thn hm m ta c 3 cch s dng trong c 1 cch nh l lc khai bo: kiu_hm_m (...,kiu_hm_con(*tn_con_tr_hm)(kiu_cc_i), ...) { /* trong thn hm m , vic truy nhp ti cc i l con tr hm */ /* c 3 cch nh nhau gi s dng cc con tr hm*/ (tn_con_tr_hm) (ds_cc_i_thc_s); (*tn_con_tr_hm) (ds_cc_i_thc_s); tn_con_tr_hm (ds_cc_i_thc_s); } - V d Danh sch cc i ca hm m kiu_hm_m float { tn hm m f( ... dng (*g)(x,y) dng (g)(x,y) dng g(x,y) } - Cc con tr hm c s dng mt cch hnh thc trong thn hm m v ch c ngha khi c li gi hm m. Li gi hm m s thay th con tr hm bng mt hm thc s no c ngha, chng hn l cc hm sin, cos, hay mt hm xc nh t trc, chng hn hm f(x)=ax2+bx+c. iu c ngha l ch cn bit cch m t dng khai bo mt con tr hm ph hp vi cc hm thc t ch khng cn xy dng ni dung c th cho con tr hm . i 1 (*g)(int,int) i 2 ,float a i 3 ,float b)

V d 1 V d sau y xt mt hm xc nh f(x) = ax2 v ta nh dng hm ny lm i ca hm g no , chng hn g(x) = (ax2 )2. Khi , i ca hm g trc ht phi l mt i hnh thc l mt con tr hm *pf no . Khi gi hm g th i f thc s mi thay th *pf.
#include <stdio.h> #include <conio.h> double f(double a,double x) {return a*x*x;} double g(double (*pf)(double,double),double a, double x) {double z = (*pf)(a,x)*(pf)(a,x); return z; } main() { double a,x; a=2; x=3; printf("\n g(%0.1f,%0.1f,%0.1f) = %0.1f", f(a,x), a, x, g(f,a,x) ); getch(); }

- Ngoi ra, con tr hm (l i ca hm m) khng c khai bo danh sch i k c hnh thc. Chng hn khai bo trn m sa nh sau l sai:
double g(double (*pf)(double a,double x)) {double z = (*pf)(a,x)*(pf)(a,x); return z; }

V khi gi hm g, tn hm thc s c thay th i hnh thc v ch l tn hm, ch khng cn ch r i! Tr trng hp con tr hm c s dng thay th cho mt hm thc s v con tr hm khng l i ca hm m no (xem v d 3)
printf("\n g(%0.1f) = %0.1f " , x, g(f,a,x) );

(ch vit l f , ch khng vit l f(a,x) , nh bn thn hm f nh ngha) V d 2 Phng php hnh thang tnh gn ng tch phn ca hm f(x) trn on [a,b] vi khong chia N m t nh sau:

Trn on [a,b], gm N khong chia, mi khong c ln: h = (b-a)/N gi s l gi tr trung bnh ca hm f(x) gia on [a,b], tc l: s = ( f(a) + f(b) ) /2 Khi , gi tr tch phn cn tnh l gi tr gn ng ca chui khai trin s = h* [ f(a+h) + f(a+2h) + ... + f(a+N*h);] Vn dng phng php hnh thang tnh tch phn nh m t trn vi s khong chia l N = 1000, hy tnh tch phn gn ng cho cc hm: 1) sin(x) trn on [0,pi/2] 2) cos(x) trn on [0,pi/2] 3) ex trn on [0,1] 4) g(x) = ex - 2sin(x2) / (1 + x4) trn on [-1.2, 3.5]
#include <stdio.h> #include <conio.h> #include <math.h> const N = 1000; const pi = 3.1416; double g(double x) { double s; s=(exp(x)-2*sin(x*x)) / (1+pow(x,4)); return s; } double tichphan(double (*pf)(double), double a,double b) {double h = (b-a)/N; double s =((*pf)(a) + (*pf)(b))/2; int i; for(i=1;i<=N;i++) s+=(*pf)(a+i*h); return h*s; } main(){ printf("\n Tich phan cua sin(x)= %0.1f", tichphan(sin, 0, pi/2) ); printf("\n Tich phan cua cos(x)= %0.1f", tichphan(cos, 0, pi/2) ); printf("\n Tich phan cua exp(x)= %0.1f", tichphan(exp, 0, pi/2) ); printf("\n Tich phan cua g(x)= %0.1f", tichphan(g, 0, pi/2) ); getch(); }

V d 3 S dng mng con tr hm lp bng gi tr cho cc hm : x2, sin(x), cos(x), ex v sqrt(x) vi x trong on [1,10] vi s gia bc tng l 0.5. - V d 2 l mt chng minh rng vic s dng con tr hm c vai tr quan trng khi mun xy dng mt ng dng m trong c nhiu hm khc nhau c s dng cng mt cch nh nhau. - i khi cho thun tin, cc hm thc s c biu th bi mt mng cc con tr hm. Chng hn nh v d 3 di y, mng con tr hm (*mf[5])(double) s ln lt biu th cc hm thc s, ngha l trc khi gi hm m (vi i l con tr hm), cc hm thc s c gn cho cc phn t ca mng con tr hm. V d 3 cng minh ha cch s dng con tr hm c lp (khng l i ca hm m no) : khi vn khng c ch r tn tham s hnh thc trong i ca con tr hm tr lc gi hm; v khng cn xy dng ni dung ca con tr hm.
#include <stdio.h> #include <conio.h> #include <math.h> double g(double x) {return x*x;} main(){ double (*mf[6])(double); mf[1]=g; mf[2]=sin; mf[3]=cos; mf[4]=exp; mf[5]=sqrt; clrscr(); { int i; double x=1.0; while(x<=10.0){ printf("\n"); for(i=1;i<5;i++) printf("%10.2f",mf[i](x)); x+=0.5;} } getch();

V d 4 Vit chng trnh nhp mt s nguyn trong on [1..3] tng ng cho tnh o hm ca cc hm s y=x2, y=x3, y=x4. Vic tnh o hm c thc hin bng mt li gi ti mt phn t mng ca hm ly mc chn lm ch s. Vit 3 hm thnh phn ca mng tnh o hm cho tng trng hp.
#include <stdio.h> #include <conio.h> #include <math.h> float f(float x) {return 2*x;} float g(float x) {return 3*x*x;} float h(float x) {return 4*x*x*x;} main(){ float (*mf[4])(float); mf[1]=f; mf[2]=g; mf[3]=h; clrscr(); { int i; float x; printf("\n nhap thu tu ham can tinh dao ham: "); scanf("%d",&i); printf("\n can tinh dao ham tai diem x= "); scanf("%f",&x); printf("gia tri dao ham can tinh la: %0.1f",mf[i](x)); } getch(); }

Bi 3. CON TR V MNG MT CHIU

1. a ch v gi tr ca cc phn t ca mng
- Mt vi l lun di y s l c s l gich cho h thng cc quy c v a ch ca mng v cc phn t ca mng: Mt cch hp l thy rng a ch ca mt c quan X gm dy nh 34, 35, 36 nm trn ph Y s l a ch ca ngi nh u tin , ngha l c quan X a ch 34 ph Y. Tng t nh th nu px l mt con tr nguyn va xin cp pht n vng b nh n*2 byte th a ch ca bin ng u tin chnh l a ch chung ca ton dy (v thi quen quy c) , ngha l a ch b nh ca 2 byte u tin trong dy n cc 2 byte b nh va xin cp pht. Cng tng t nh th, mt mng nguyn a th &a[0] l a ch ca phn t u tin ca mng ng thi cng l a ch ca ton mng , ngha l a = &a[0] Mt khc, nu px l mt con tr nguyn ca dy n cc 2 bye b nh th php ton tng con tr px = px + i ngha l cho px tr vo 2 byte th i trong dy n cc 2 byte b nh . Tng t nh th, mng a kiu nguyn c th coi l mt con tr: tr vo dy cc 2 byte b nh, v , khi th php ton tng a ch a + i chnh l truy nhp ti a ch ca phn t th i trong mng a, do (a+i) = &a[i], v cng v vy ta c *(a+i) = a[i] - Tm li ta c h thng cc biu din ng nht nh sau: h thng (1) a==&a[0] a+1== &a[1] a+2==&a[2] ... a+i==&a[i] *(a+i)==a[i] - Mt cch gin tip, nu ta c khai bo float a[n]; float *pa; pa=a; th pa c th thay th a trong h thng (1)

ngha l ta c: H thng (2) a[i] c a ch &a[i] *(a+i) c a ch a+i *(pa+i) c a ch pa+i pa[i] c a ch &pa[i] Trong : a[i] == *(a+i) == *(pa+i)==pa[i] &a[i]== (a+i)== (pa+i)==&pa[i] V d 1 Nhp mt mng float v sp xp tng dn cc phn t trong mng
#include <stdio.h> #include <conio.h> main(){ float a[10]; int n,i,j; float tg; printf("\n nhap n: "); scanf("%d",&n); for(i=0;i<n;i++) {printf("a[%d]=",i+1); scanf("%f",(a+i)); } for(i=0;i<n-1;i++) for(j=i+1;j<n;j++) if(a[j]<a[i]) {tg=*(a+i); *(a+i)=*(a+j); *(a+j)=tg; } printf("\n sau khi sap xep :"); for(i=0;i<n;i++) printf("%0.1f ",a[i]); getch(); }

- Lnh scanf(%f, (a+i)); c th vit l scanf(%f, &a[i]); - Cc lnh tg=*(a+i); *(a+i)=*(a+j); *(a+j)=tg; c th vit n gin l: tg=a[i]; a[i]=a[j]; a[j]=tg; vv...

2. i ca hm (i ra) l mng th l mt con tr


- H thng 1 cho thy bn thn mng v con tr c quan h cht ch: cc phn t ca mng c xc nh nh ch s hoc thng qua con tr. - H thng 2 l cch s dng con tr mng mt cch gin tip nu mun truyn i cho hm l mt mng. - Gi s a l mt mng, maxN l mt hng s xc nh, *pa l mt bin con tr c kiu trng vi kiu ca mng ( sau ny thay tham s hnh thc pa bi tham s thc s (cng kiu) l a), n l s phn t c th ca mng a. Ta c cc quy nh sau y v c php: - Khai bo: . kiu_dl_mng a[maxN]; . kiu_dl_hm tn_hm( kiu_mng *pa, int n) { Thn hm: - a ch ca phn t th i l (pa+i) - gi tr ca phn t th i l *(pa+i) hoc pa[i] } - S dng: tn_hm(a,n); ngha l thay tham s hnh thc *pa bng a. (a l mt con tr mng, *pa l mt con tr kiu_dl_mng) V d 2 Xy dng cc hm thc hin cc nhim v sau y: - Nhp mt mng n s thc - In mng nhp ln mn hnh - Sp xp cc phn t ca mng theo th t tng dn trong hm main, gi thc hin cc hm ni trn.
#include <stdio.h> #include <conio.h> void nhapmang(float *pa,int *n)

int i; printf("\n nhap n: "); scanf("%d",n); for(i=0;i<*n;i++) { printf("a[%d]=",i+1); scanf("%f",(pa+i)); }

} void sapxep(float *pa, int n) { int i,j; float tg; for(i=0;i<n-1;i++) for(j=i+1;j<n;j++) if(pa[j]<pa[i]){tg=pa[i]; pa[i]=pa[j]; pa[j]=tg; } } void inmang(float *pa,int n) { int i; for(i=0;i<n;i++) printf("%0.1f ",pa[i]); } main(){ float a[10]; int n; nhapmang(a,&n); printf("\n truoc khi sap xep: "); inmang(a,n); printf("\n sau khi sap xep: "); sapxep(a,n); inmang(a,n); getch(); }

Bi 4. CON TR V MNG 2 CHIU

1. Nguyn tc vit a ch v gi tr ca cc phn t mng ca 2 chiu


- Xt mt mng a, a ch ca phn t a[i][j] vit l &a[i,j] hay &a[i][j] u sai. Do vy, s dng gi tr ca phn t a[i,j] ta vn c th vit a[i][j] , nhng nu nhp th khng th vit scanf(%f,&a[i][j]); i khi phc tp (nh s di y), ta dng thm bin trung gian x nhp cho &x v sau gn a[i][j]=x; - Nguyn tc vit a ch v gi tr ca cc phn t ca mng 2 chiu c tm tt nh s sau y:
float a[][n]; hoc float a[m][n]; (1) (1)

a[i,j]

(float*)a +i*n+j c a ch float *pa; v gn pa = (float*)a; (2) (3)

* ( (float*)a +i*n+j ) c gi tr nu khai bo thm (2) v lnh trao a ch (3)

a[i,j]

pa + i*n + j c a ch

*(pa + i*n + j) c gi tr

Lu : nu trong (3), ch gn pa=a s sai v v tri l bin con tr float, v phi l con tr float[m]. So snh 3 cch trong 3 v d sau y nhp v in mng 2 chiu va nhp. V d 1
#include <stdio.h> #include <conio.h> #define maxm 100 #define maxn 100 main() { float a[maxm][maxn]; int i,j,m,n; printf("\n nhap m,n : "); scanf("%d%d",&m,&n); for(i=0;i<m;i++) for(j=0;j<n;j++) { printf("a[%d,%d]= ",i,j); scanf("%f", (float*)a+i*n+j); } printf("\n mang vua nhap la:\n "); for(i=0;i<m;i++) { for(j=0;j<n;j++) printf("%3.1f\t", *( (float*)a +i*n +j) ); printf("\n"); } getch(); }

Cc c php : scanf("%f", (float*)a+i*n+j); (1) v printf("%3.1f\t", *( (float*)a +i*n +j) ); (2) c v phc tp. khc phc, ta dng thm mt bin trung gian x nh v d 2 sau y: V d 2
#include <stdio.h> #include <conio.h> #define maxm 100 #define maxn 100

main() { float a[maxm][maxn]; int i,j,m,n; float x; printf("\n nhap m,n : "); scanf("%d%d",&m,&n); for(i=0;i<m;i++) for(j=0;j<n;j++) { printf("a[%d,%d]= ",i,j); scanf("%f", &x); a[i][j]=x; } printf("\n mang vua nhap la:\n "); for(i=0;i<m;i++) { for(j=0;j<n;j++) printf("%3.1f\t", a[i][j]); printf("\n"); } getch(); }

Vic s dng thm bin trung gian x thay c phc tp (1) v (2) thnh
scanf("%f", &x); a[i][j]=x; (1b)

v
printf("%3.1f\t", a[i][j]); (2b)

Lu rng (1) khng th i cng vi (2b) v (1b) cng khng th i cng vi (2) Mt cch th 3 l ta dng thm mt con tr mng nh v d sau y: V d 3
#include <stdio.h> #include <conio.h> #define maxm 100 #define maxn 100 main() { float a[maxm][maxn]; int i,j,m,n; float *pa; pa=(float*)a; printf("\n nhap m,n : "); scanf("%d%d",&m,&n); for(i=0;i<m;i++) for(j=0;j<n;j++) { printf("a[%d,%d]= ",i,j);

scanf("%f", pa+i*n+j); } printf("\n mang vua nhap la:\n "); for(i=0;i<m;i++) { for(j=0;j<n;j++) printf("%3.1f\t", *(pa+i*n+j) ) ; printf("\n"); } getch(); }

ng nh s : vic s dng thm con tr float *pa ; vi lnh gn pa=(float*)a; l mt p kiu th cho php din t n gin (1) v (2) nhp: scanf("%f", pa+i*n+j); in gi tr : printf("%3.1f\t", *(pa+i*n+j) ) ; * T ta thy rng, nu thao tc vi mng mt cch trc tip trong hm main() hoc vi mt mng t ng trong mt hm th nn s dng c php ca v d 2. Nu mun truyn mng vo hm nh mt i ca hm th phi s dng c php ca v d 3, ngha l s dng bin con tr, xem mc 2 di y.

2. i ca hm (i ra) l mt mng 2 chiu th phi l con tr mng


- Khai bo: kiu_mng a[m][n]; kiu_hm tn_hm( kiu_mng *pa, int m, int n) - Thn hm { + a ch ca a[i,j] l: (pa+i*n+j) + gi tr ca a[i,j] l: *(pa+i*n+j) } - Khi s dng: tn_hm( (kiu_mng*)a, m, n )

- C th thc hin cch th 2 : ta dng thm mt bin con tr trung gian , gi s kiu mng a l float float a[m][n]; float *pa; pa = (float*)a; . Khai bo kiu_hm tn_hm ( float (*pa)[n] ) hoc kiu_hm tn_hm ( float pa[][n] ) . Thn hm Cch vit pa[i][j] s dng gi tr. Nu mun s dng a ch , chng hn nhp th c th dng thm mt bin trung gian, nh v d 1. V d 4 Vit cc hm: - Nhp ma trn cc phn t ca mt ma trn l cc s thc bit kch thc mxn. - In ln mn hnh ma trn kch thc mxn. - Tnh ma trn tch C[mxn]= A[mxp]*B[pxn] Vn dng cc hm trn, trong hm main() thc hin cc cng vic sau y: - Nhp cc s nguyn m,p,n . - Nhp cc ma trn A[mxp], B[pxn] cc phn t l cc s thc - In ln mn hnh cc ma trn A, B, C = A*B
#include <stdio.h> #include <conio.h> #define size 100 void nhapmatran(float*,int,int); void inmatran(float*,int,int); void tinhtich(float*,float*,float*,int,int,int); void main() { float a[size][size], b[size][size], c[size][size]; int m,p,n; printf("\n nhap m,p,n : "); scanf("%d%d%d",&m,&p,&n); printf("\n nhap ma tran a:\n"); nhapmatran((float*)a,m,p); printf("\n nhap ma tran b:\n"); nhapmatran((float*)b,p,n); tinhtich((float*)a,(float*)b,(float*)c,m,p,n);

inmatran((float*)a,m,p); inmatran((float*)b,p,n); inmatran((float*)c,m,n); getch(); } void nhapmatran(float *pa,int m,int n) { int i,j; for(i=0;i<m;i++) for(j=0;j<n;j++) {printf("item[%d,%d]= ",i+1,j+1); scanf("%f",(pa+i*n+j)); } } void inmatran(float *pa,int m,int n) { int i,j; for(i=0;i<m;i++) { for(j=0;j<n;j++) printf("%10.1f",*(pa+i*n+j)); printf("\n"); } printf("\n\n"); } void tinhtich(float *pa,float *pb,float *pc,int m,int p,int n) { int i,j,k; for(i=0;i<m;i++) for(j=0;j<n;j++) { *(pc+i*n+j)=0; for(k=0;k<p;k++) *(pc+i*n+j) += (*(pa+i*p+k)) * (*(pb+k*n+j)); } }

Chng 4. CON TR, K T V XU K T


Bi 1. Mng cc phn t l cc xu k t
C 3 mu nhp v x l mt danh sch m mi phn t ca danh sch l mt xu k t. - Hai mu u tin (mc 1 v 2) biu din danh sch cc xu k t bng mng con tr kiu char. Do mi phn t ca mng l mt con tr kiu char c kh nng biu din mt xu k t. Mu 3 (mc 3) biu din danh sch cc xu k t bng mt mng 2 chiu m mi mt hng ca mng l mt dy cc k t. Vi cch biu din ny t nhiu c nhng hn ch khi mun x l tng phn t (xu k t) ca danh sch. - Mu (1) c p dng khi x l trc tip trong chng trnh mt danh sch cc xu k t, c th i ch cc phn t ca danh sch cho nhau, c th x l tng k t trn tng phn t. - Mu (2) c tc dng nh mu (1) nhng c p dng trong trng hp mun truyn i l danh sch cc xu k t cho hm x l.

1. Mng cc phn t l xu k t trong chng trnh (hm main())

1.1. Khai bo
# define maxn 100; # define maxlen 50; char *s[maxn]; int n; char tg[maxlen]; int len,i,j;

1.2. Nhp
for(i=0;i<n;i++) { printf(s[%d] =,i); gets(tg); len=strlen(tg); s[i]= (char*) malloc ((len+1)*sizeof(char)); }

1.3. In danh sch


for(i=0;i<n;i++) printf(%s\n,s[i]);

1.4. X l
- o ngc danh sch, s dng cc php gn for(i=0,j=n-1; i<j ; i++, j--) { strcpy(tg,s[i]); strcpy(s[i], s[j]); strcpy(s[j],tg); }

- Mi phn t th i ca danh sch s l mt xu k t, ta c th x l tng k t th j trong xu k t s[i] , ta vit s[i][j]


for(i=0;i<n;i++){ for(j=0;j<strlen(s[i]);j++) <x l s[i][j]>}

Xem cc v d 1,2

2. i (i ra) ca hm l mng cc xu k t

2.1. Khai bo
# define maxn 100; # define maxlen 50; char *s[maxn]; int n;

2.2. Vit hm
kiu_hm tn_hm (char *ps[], int n)

{ thn hm:
phn t th i ca mng l ps[i] , ps[i] l mt xu k t }

2.3. Gi hm
nhap_ds(s,&n); in_ds(s,n); dao_ds(s,n); in_ds(s,n); ... Xem cc v d 3,4

3. Mng cc xu k t biu din bng mng 2 chiu cc k t


Trong trng hp mng cc xu k t c s dng : - Khng truyn i cho hm - Khng c nhu cu thay i gi tr ca cc xu k t trong danh sch th ta nn biu din n bng mt mng 2 chiu cc phn t l cc k t v s dng nh dng sau y:

3.1. Khai bo
# define maxn 100; # define maxlen 50; char s[maxn][maxlen]; int n,i,j;

3.2. Nhp
for(i=0;i<n;i++) {... gets(s[i]);}

3.3. X l
for(i=0;i<n;i++) {

... Dng (s[i]) /* hn ch x l trn xu s[i] */ ...}

V d 1
- Nhp t bn phm danh sch gm tn ca n cn b. - o ngc danh sch v in kt qu ln mn hnh. - Sp xp danh sch theo alphabe v in kt qu ln mn hnh #include <stdio.h> #include <conio.h> #include <string.h> #define maxn 100 #define maxlen 50 main() { char s[maxn][maxlen]; int n; int i,j; char tg[maxlen]; printf("\n nhap n: "); scanf("%d",&n); fflush(stdin); printf("\n nhap n ten n can bo:\n"); for(i=0;i<n;i++) {printf("\n s[%d] = ",i); gets(s[i]);} for(i=0,j=n-1; i<j; i++,j--) {strcpy(tg,s[i]); strcpy(s[i],s[j]); strcpy(s[j],tg);} printf("\n danh sach duoc dao nguoc:\n"); for(i=0;i<n;i++) puts(s[i]); for(i=0;i<n-1;i++) for(j=i+1;j<n;j++) if(strcmp(s[j],s[i])<0) {strcpy(tg,s[i]); strcpy(s[i],s[j]); strcpy(s[j],tg);} printf("\n danh sach duoc sap xep:\n"); for(i=0;i<n;i++) puts(s[i]); getch(); }

V d 2
- Nhp t bn phm danh sch gm tn ca n sinh vin - Sp xp danh sch theo alphabe v in kt qu ln mn hnh #include <stdio.h> #include <conio.h> #include <string.h> #define maxn 100 #define maxlen 50

main() { char *s[maxn]; char tg[maxlen]; int n; int i,j; printf("\n nhap n: "); scanf("%d",&n); fflush(stdin); printf("\n nhap n xau ky tu:\n"); for(i=0;i<n;i++) { int len; printf("\n s[%d] = ",i); gets(tg); len=strlen(tg); s[i]=(char*) malloc ((len+1)*sizeof(char)); strcpy(s[i],tg); } for(i=0;i<n-1;i++) for(j=i+1;j<n;j++) if(strcmp(s[j],s[i])<0) { strcpy(tg,s[i]); strcpy(s[i],s[j]); strcpy(s[j],tg);} printf("\n danh sach sau khi sap xep la:\n"); for(i=0;i<n;i++) printf("%s\t",s[i]); getch();}

V d 3
- Nhp t bn phm danh sch gm h v tn ca n sinh vin - Cha li cc ch ci u ca h v tn mi sinh vin l mt ch hoa - In kt qu ln mn hnh #include <stdio.h> #include <conio.h> #include <string.h> #define maxn 100 #define maxlen 50 main() { char *s[maxn]; char tg[maxlen]; int n; int i,j; printf("\n nhap n: "); scanf("%d",&n); fflush(stdin); printf("\n nhap n xau ky tu:\n"); for(i=0;i<n;i++) { int len; printf("\n s[%d] = ",i); gets(tg); len=strlen(tg); s[i]=(char*) malloc ((len+1)*sizeof(char)); strcpy(s[i],tg); } for(i=0;i<n;i++) for(j=0;j<strlen(s[i]);j++)

if(j==0 || (s[i][j-1]==32 && s[i][j]!=32)) { s[i][j]-=32;} printf("\n danh sach sau khi sua:\n"); for(i=0;i<n;i++) printf("\n%s",s[i]); getch(); } V d 3 Vit chng trnh minh ha s dng cc hm sau y: - Nhp mt danh sch tn cc mt hng - In danh sch cc tn mt hng. - Tm kim mt mt hng bit tn mt hng nhp t bn phm #include <stdio.h> #include <conio.h> #include <string.h> #define maxn 100 #define maxlen 50 void nhap_ds(char *ps[],int *n) { int i; char tg[maxlen]; printf("\n nhap n: "); scanf("%d",n); fflush(stdin); printf("\n nhap n ten mat hang:\n"); for(i=0;i<*n;i++) { int len; printf("\n s[%d] = ",i); gets(tg); len=strlen(tg); ps[i]=(char*) malloc ((len+1)*sizeof(char)); strcpy(ps[i],tg); } } void in_ds(char *ps[],int n) { int i; printf("\n danh sach cac mat hang:\n"); for(i=0;i<n;i++) printf("%s\t",ps[i]); } int timthay(char *s,char *ps[],int n) { int i,j=0; for(i=0;i<n;i++) if(strcmp(s,ps[i])==0) j=1; return j; }

main() { char *s[maxn]; int n; char tenh[maxlen]; nhap_ds(s,&n); in_ds(s,n); printf("\n nhap ten mot mat hang can tim : "); scanf("%s",tenh); if (timthay(tenh,s,n)) printf("\n co ten hang nay trong danh sach"); else printf("\n khong co ten hang nay trong danh sach"); getch(); } V d 4 Xy dng cc hm sau v minh ha vic s dng chng trong main() - Nhp t bn phm tn ca n sinh vin - Sp xp danh sch tn cc sinh vn theo th t gim dn - In danh sch sinh vin ln mn hnh #include <stdio.h> #include <conio.h> #include <string.h> #define maxn 100 #define maxlen 50 void nhap_ds(char *ps[],int *n) { int i; char tg[maxlen]; printf("\n nhap n: "); scanf("%d",n); fflush(stdin); printf("\n nhap n ten n nhan vien:\n"); for(i=0;i<*n;i++) { int len; printf("\n s[%d] = ",i); gets(tg); len=strlen(tg); ps[i]=(char*) malloc ((len+1)*sizeof(char)); strcpy(ps[i],tg); } } void in_ds(char *ps[],int n) { int i; printf("\n danh sach cac nhan vien:\n"); for(i=0;i<n;i++) printf("%s\t",ps[i]); } void sapxep(char *ps[],int n) { int i,j;

char tg[maxlen]; for(i=0;i<n-1;i++) for(j=i+1;j<n;j++) if(strcmp(ps[j],ps[i])>0) {strcpy(tg,ps[i]); strcpy(ps[i],ps[j]); strcpy(ps[j],tg);} } main() { char *s[maxn]; int n; nhap_ds(s,&n); sapxep(s,n); in_ds(s,n); getch(); }

Bi 2. Mng cc phn t l k t
1. Nhc li v vn cp pht b nh cho bin ng v dy bin ng
Nu p l bin con tr th p c 2 tc dng - cha a ch ca bin, mng. - cp pht b nh cho bin ng: Gi s p c kiu TypeP TypeP *p; 1) Cp pht b nh cho n bin ng kiu TypeP v xc nh bng con tr p, ta vit lnh p = (TypeP*) malloc ((n+1)*sizeof(TypeP) 2) Khi truy nhp ti dy n bin ng bng lnh: for (i=0; i<n ; i++) < su dung p[i]> 3) gii phng b nh cho dy bin ng ny , ta dng lnh for (i=0; i<n ; i++) free(p[i]);

2. Mng cc phn t l k t, s dng con tr kiu char.

2.1. Khai bo
char *s; char st[20]; int len;

2.2. Nhp mng k t , cp pht b nh ng


gets(st); len=strcpy(st); s=(char*) malloc (len+1);

strcpy(s,st);

2.3. Duyt mng in


for(i=0;i<len;i++) printf("%c",*(s+i))

2.4. Sp xp cc k t trong mng k t


Thm mt bin char *p; p = (char*) malloc (2) V p dng thut ton sp xp for(i=0;i<len;i++) for(j=len-1;j>i;j--) if(*(s+j)<*(s+j-1)) { *p=*(s+j); *(s+j)=*(s+j-1); *(s+j-1)=*(s+j); } 3. Tm hiu v con tr kiu char
void main() { char *s; char *p; char st[25]; int len; int i,j; printf("\ns = "); gets(st); len=strlen(st); s=(char*) malloc (len+1); strcpy(s,st); for(i=0;i<len;i++) printf("%c",*(s+i)); printf("\n"); p=s; for(i=0;i<len;i++) {printf("%c",*s); s++;} ; printf("\n"); s=p; for(i=0;i<len;i++) {printf("%c",*s); s++;} ; printf("\n"); getch(); }

V d
Nhp mt xu k t t bn phm gm cc ch ci. Hy chuyn cc ch hoa ln u, cc ch thng v cui dy sao cho th t trc sau ca tng loi ch hoa, ch thng trong dy ban u c gi nguyn.

Cch 1/* Dung con tro kieu char */


#include <stdio.h> #include <string.h> #include <ctype.h> void main() { char *s; char *p; char st[25]; int len; int i,j; clrscr(); printf("\ns = "); gets(st); len=strlen(st); s=(char*) malloc (len+1); strcpy(s,st); for(i=0;i<len;i++) printf("%c",*(s+i)); printf("\n"); p=(char*) malloc (1); for(i=1;i<len;i++) for(j=len-1;j>=i;j--) if( isupper(*(s+j)) && islower(*(s+j-1)) ) { *p=*(s+j); *(s+j)=*(s+j-1); *(s+j-1)=*p; } for(i=0;i<len;i++) printf("%c",*(s+i)); printf("\n"); getch(); }

Cch 2 /* Dung mang kieu char */


#include <stdio.h>#include <string.h>#include <ctype.h>void main(){ char s[200]; int i,j; int len,k; clrscr(); printf("\ns = "); gets(s); printf("\ns= "); puts(s); len=strlen(s); for(i=1;i<len;i++) for(j=len-1;j>=i;j--) if( isupper(s[j]) && islower(s[j-1]) ) { k=s[j]; s[j]=s[j-1]; s[j-1]=k; } printf("\ns= "); puts(s); getch(); }

Bi 3. Xy dng cc php ton tin ch trn xu k t


1. Xem xt cc hm c sn trong C

1.1. Cc hm chuyn i kiu


1. Chuyn i kiu tng qut #include <stdio.h> int sprintf(char *s,char *dkhien, danh_sach_doi); V d sprintf(s,"%s %s %s",s1,s2,s3); 2. Trong <ctype.h> int tolower(int c); i 1 ch hoa thnh ch thng. int toupper(int c); i 1 ch thng thnh ch hoa. double atof(char *s); Chuyn chui s sang gi tr double. int atoi(char *s); Chuyn chui s sang gi tr int. long atol(char *s); Chuyn chui s sang gi tr long. char *itoa(int x,char *s,int cs); Chuyn s nguyn x h cs thnh chui s . Hm tr v a ch ca s. char *ltoa(long x, char *s,int cs); Tng t nh hm itoa(x,s,cs) char *gcvt(double x, int n, char *s);

- Chuyn double sang chui s gm cc ch s, c c du chm thp phn v du cho s m :


- Vo + x : gi tr double cn chuyn. + n : s ch s c ngha cn lu gi. - Ra + Chui kt qu ( dng thp phn hoc dng m ) cha trong vng s. + Hm tr v a ch vng s.

1.2. Cc hm kim tra k t


int isalnum(int kt); int isalpha(int kt); int islower(int kt); int upper(int kt); int isspace(int kt); int isdigit(int kt); int isxdigit(int kt); kt c phi l ch s h 16 khng int ispunct(int kt); kt c phi du chm cu. int isgraph(int kt); kt c phi l k t in c (khc k t trng 0x21 n 0x7E) int isprint(int kt); kt c phi l k t in c (k c k t trng 0x20 n 0x7E)

1.3. Cc hm trn xu k t
1. 2.
3. 4. 5. 6. 7. 8. int strlen(char *s) char *strcat(char *s1, char *s2) char *strncat(char *s1, char *s2) char strcpy(char *s1, char *s2) char strncpy(char *s1,char *s2,int n) int strcspn(char *s1, char *s2) int strspn(char *s1, char *s2) char strstr(char *s1, char *s2) di chui B sung chui s2 vo sau chui s1. Ghp n k t u tin ca s2 vo s1 Sao chp chui s2 vo vng s1. Sao chp n k t u ca s2 sang s1. Cho on u di nht ca s1 m khng k t no ca s1 c mt trong s2 Cho on u di nht ca s1 m mi k t trong on c mt trong s2 Tm v tr xut hin ca chui s2 trong s1. Nu thy, hm tr li a ch ca chui con trong s1. Tri li, hm cho gi tr NULL. Tm v tr u tin ca k t kt trong s , hm cho a ch ca kt trong chui. Tm v cui cng ca k t kt trong s : , hm cho a ch ca kt trong chui. Tm s xut hin u tin ca mt k t ca s2 trong s1. Nu c xut hin, hm cho a ch ca k t tm thy trong s1. Ngc li , hm cho gi tr NULL. So snh 2 chui. Hm cho gi tr m nu s1<s2, 0 nu s1=s2, dng nu s1>s2 So snh 2 chui khng phn bit ch hoa v ch thng. So snh 2 chui khng phn bit ch hoa v ch thng. ( nh hm strcmpi) So snh n k t u tin ca 2 chui . So snh n k t u tin ca 2 chui , khng phn bit ch hoa , ch thng. i ch hoa thnh ch thng i ch thng thnh ch hoa Gp i mt chui. o ngc chui s. Kt qu s s gm n k t c. Thay mi k t trong s bng kt

9.

char strchr(char *s, int kt)

10. char strrchr(char *s, int kt) 11. char *strpbrk(char *s1,char *s2)

12. int strcmp(char *s1, char *s2) 13. int strcmpi(char *s1, char *s2) 14. int stricmp(char *s1, char *s2) 15. int strncmp(char *s1, char *s2, int n) 16. int strnicmp(char *s1,char *s2, int n) 17. 18. 19. 20. 21. 22.
char *strlwr(char *s) char *strupr(char *s) char *strdup(char *s) char *strrev(char *s) char *strnset(char *s,int c,int n) char *strset(char *s,int kt)

1.4. Phn bit mt s hm


Trong stdio.h char *gets( char *s) Nhp mt chui k t t stdin , tr v a ch ca chui, s l bin con Trong conio.h getch() : Nhn k t t b m bn phm, khng hin ln mn hnh.

tr ( kiu char) tr ti vng nh cha dy k t nhn c. int puts(const char *s) a chui s ln mn hnh v a c k t '\n' ln mn hnh , do sau khi in xong s th con tr mn hnh chuyn xung dng di . int getchar(void) : Nhn mt k t t stdin v hm tr v k t . int putchar(int ch) :a gi tr k t ch ln mn hnh .

getche() : Nhn k t t b m bn phm, c hin ln mn hnh. putch() : a mt k t ln mn hnh vn bn, c mu sc theo lnh textcolor, trong khi , hm putchar() lun hin k t c mu trng kbhit() : Cho bit trong b m bn phm cn kt no khng

2. Xy dng cc hm tin ch trn xu k t

2.1. Hm copy
/* tao ham copy(s,i,n) trong tc */ /* van dung : dem so tu x trong cau van s */ #include <stdio.h> #define max 200 char *copy(char *s,int k,int n); void main() { char x[max],s[max]; int k,lx,d=0; clrscr(); printf("nhap chuoi s : "); gets(s); printf("nhap chuoi x : "); gets(x); lx=strlen(x); for(k=0;s[k]!='\0';k++) if(strcmp(x,copy(s,k,lx))==0) d++; printf("\n%d",d); getch(); } char *copy(char *s,int k,int n) { int i,j=0; char s1[max]; for(i=0;s[i]!='\0';i++) if((i>=k)&&(j<n)) {s1[j]=s[i];j++;} s1[j]='\0'; return(s1); }

2.2. Hm clean
/* Xoa cac dau cach vo nghia trong cau */ /* Xay dung ham clean(s) */

#include <stdio.h> #include <ctype.h> #define max 100 char *clean(char *s); void myprintf(char *s); void main() { char s[max]; clrscr(); printf("nhap chuoi s : "); gets(s); myprintf(clean(s)); getch(); } char *clean(char *s) { int t,p,i,j=0; char s1[max]; t=0; while (isspace(s[t])) t++; p=strlen(s)-1; while (isspace(s[p])) p--; for(i=t;i<=p;i++) if( !isspace(s[i]) || (isspace(s[i]) && !isspace(s[i+1]) )) {s1[j]=s[i];j++;} s1[j]='\0'; return(s1); } void myprintf(char *s) { int i; for(i=0;s[i]!='\0';i++) if (isspace(s[i])) putchar('_'); else putchar(s[i]); printf("\n"); }

2.3. Cc hm insert, delete, pos


/* xay dung cac ham - insert(x,s,k) */ /* - delete(s,k,n) */ /* - copy(s,k,n) */ /* - pos(x,s) */ /* van dung, sua loi cu phap ve dau phay va dau cham */ /* - sytax(s,symbol) */ #include <stdio.h> #include <ctype.h> #define max 100 #define sperator ','

#define pointstop '.' char *insert(char *x,char *s,int k); char *delete(char *s,int k,int n); char *copy(char *s,int k,int n); int pos(char *x,char *s); char *sytax(char *s,char symbol); void myprintf(char *s); void main() { char s[max],x[max]; printf("nhap chuoi s : "); gets(s); myprintf(s); sytax(s,sperator); sytax(s,pointstop); myprintf(s); getch(); } char *insert(char *x,char *s,int k) { int i,j1=0,j2=0; char s1[max],s2[max]; for(i=0;i<k;i++) {s1[j1]=s[i];j1++;} for(i=k;s[i]!='\0';i++) {s2[j2]=s[i];j2++;} s1[j1]='\0'; s2[j2]='\0'; sprintf(s,"%s%s%s",s1,x,s2); return(s); } char *delete(char *s,int k,int n) { int i,j1=0,j2=0; char s1[max],s2[max]; for(i=0;i<k;i++) {s1[j1]=s[i];j1++;} for(i=k+n;s[i]!='\0';i++) {s2[j2]=s[i];j2++;} s1[j1]='\0'; s2[j2]='\0'; sprintf(s,"%s%s",s1,s2); return(s); } char *copy(char *s,int k,int n) { int i,j=0; char s1[max]; for(i=0;s[i]!='\0';i++) if((i>=k)&&(j<n)) {s1[j]=s[i];j++;} s1[j]='\0'; return(s1); } int pos(char *x,char *s) {

int lx,i,d=-1; lx=strlen(x); for(i=0;s[i]!='\0';i++) if (strcmp(copy(s,i,lx),x)==0) {d=i; break; } return(d); } char *sytax(char *s,char symbol) { #define space ' ' #define error1 " ," #define error2 ", " #define error3 " ." #define error4 ". " int k,ls,i=0; ls=strlen(s); while(i<ls) { if(s[i]==symbol) insert(" ",s,++i); i++;} if (symbol==sperator) { while((k=pos(error1,s))>-1) delete(s,k,1); while((k=pos(error2,s))>-1) delete(s,k+1,1);} else { while((k=pos(error3,s))>-1) delete(s,k,1); while((k=pos(error4,s))>-1) delete(s,k+1,1);} return(s); } void myprintf(char *s) { int i; for(i=0;s[i]!='\0';i++) if (isspace(s[i])) putchar('*'); else putchar(s[i]); printf("\n"); }

2.3. Cc hm insert, delete, sytax nn c kiu void


/* xay dung cac ham: /* insert(x,s,k), delete(s,k,n), copy(s,k,n), pos(x,s), /* sua loi cu phap ve dau phay va dau cham: sytax(s,symbol) */ #include <stdio.h> #include <ctype.h> #define max 100 #define sperator ',' #define pointstop '.' void insert(char *x,char *s,int k); void delete(char *s,int k,int n); char *copy(char *s,int k,int n);

int pos(char *x,char *s); void sytax(char *s,char symbol); void myprintf(char *s); void main() { char s[max],x[max]; printf("nhap chuoi s : "); gets(s); myprintf(s); sytax(s,sperator); sytax(s,pointstop); myprintf(s); getch(); } void insert(char *x,char *s,int k) { int i,j1=0,j2=0; char s1[max],s2[max]; for(i=0;i<k;i++) {s1[j1]=s[i];j1++;} for(i=k;s[i]!='\0';i++) {s2[j2]=s[i];j2++;} s1[j1]='\0'; s2[j2]='\0'; sprintf(s,"%s%s%s",s1,x,s2); } void delete(char *s,int k,int n) { int i,j1=0,j2=0; char s1[max],s2[max]; for(i=0;i<k;i++) {s1[j1]=s[i];j1++;} for(i=k+n;s[i]!='\0';i++) {s2[j2]=s[i];j2++;} s1[j1]='\0'; s2[j2]='\0'; sprintf(s,"%s%s",s1,s2); } char *copy(char *s,int k,int n) { int i,j=0; char s1[max]; for(i=0;s[i]!='\0';i++) if((i>=k)&&(j<n)) {s1[j]=s[i];j++;} s1[j]='\0'; return(s1); } int pos(char *x,char *s) { int lx,i,d=-1; lx=strlen(x); for(i=0;s[i]!='\0';i++) if (strcmp(copy(s,i,lx),x)==0) {d=i; break; } return(d);

} void sytax(char *s,char symbol) { #define space ' ' #define error1 " ," #define error2 ", " #define error3 " ." #define error4 ". " int k,ls,i=0; ls=strlen(s); while(i<ls) { if(s[i]==symbol) insert(" ",s,++i); i++;} if (symbol==sperator) { while((k=pos(error1,s))>-1) delete(s,k,1); while((k=pos(error2,s))>-1) delete(s,k+1,1);} else { while((k=pos(error3,s))>-1) delete(s,k,1); while((k=pos(error4,s))>-1) delete(s,k+1,1);} } void myprintf(char *s) { int i; for(i=0;s[i]!='\0';i++) if (isspace(s[i])) putchar('*'); else putchar(s[i]); printf("\n");}

Chng 5. CU TRC V HP
Bi 1. KIU D LIU KIU CU TRC - STRUCT

1. nh ngha kiu cu trc


1.1. Khai bo struct tn_kiu_cu_trc { /*thn cu trc bao gm: */ kiu_d_liu_1 trng_1; kiu_d_liu_2 trng_2; kiu_d_liu_3 trng_3; ... } [bin_cu_trc1, bin_cu_trc2, .... ] ; - Khai bo trn c tc dng nh sau: + Khai bo mt tn kiu d liu. + Khai bo cc thnh phn ca kiu cu trc , mi thnh phn gi l trng. Mi trng c th c kiu d liu khc nhau. + Cc kiu d liu ca cc trng: C kiu d liu ni chung l ty , ngha l bao gm cc kiu d liu n gin c sn v k c kiu cu trc nu trc nh ngha kiu cu trc . + Cc bin c kiu d liu cu trc (gi tt l cc bin c kiu cu trc) c th khai bo trc tip nh trn hoc khai bo sau nh di y: struct tn_kiu_cu_trc tn_bin1, tn_bin2, ... - C th khai bo mt mng cu trc nh sau struct tn_kiu_cu_trc tn_bin_mng[s_pht_mng]; - Mt kiu d liu mi c tn_kiu_cu_trc c th khai bo nh typedef : typedef struct { /* thn cu trc */ } tn_kiu_d_liu; V khi cc bin c kiu d liu (cu trc) ny c th khai bo nh cc kiu d liu bnh thng:

tn_kiu_d_liu tnbin, tnmng[sphnt]; 1.2. V d v khai bo cu trc V d 1 khai bo cc bin sv1, sv2, sv3, sv4, mng sv[100] c kiu sinhvien, trong sinhvien l mt kiu d liu cu trc gm cc trng: - h tn - nm sinh - a ch ta c 2 cch: Cch 1: struct sinhvien { char *hoten; int namsinh; char *diachi; } sv1, sv2; struct sinhvien sv3, sv4, sv[100]; Cch 2: typedef struct { char *hoten; int namsinh; char *diachi; } sinhvien; sinhvien sv1, sv2, sv3, sv4, sv[100]; V d 2 Yu cu Khai bo trn vn l lch ca mt sinh vin. V d 2 minh ha trng hp khi no nn dng typedef, khi no th khng nn dng: typedef struct { unsigned int ngay; unsigned int thang;

unsigned int nam; } ngaysinh; typedef struct { char *tenpho; unsigned sonha; unsigned long dienthoai; } diachi; struct sinhvien { char *hoten; ngaysinh ns; diachi dc; }; struct sinhvien sv1, sv2, sv[100];

2. Cch s dng cu trc


(1)- i vi mt bin cu trc ch c cc php so snh, php gn 2 cu trc cng kiu. (2)- Cc trng ca cu trc c th c cc php ton ton ty thuc vo kiu d liu ca n. Nu trng c kiu d liu n gin th thm ch c th ly a ch ca n. (3)- Cc trng ca cu trc trng s dng thng qua ton t xc nh (du chm) tn_kiu_cu_trc.tn_trng (4)- Khi truy nhp vo trng th phi truy nhp n trng nh nht , tc l trng c kiu d liu n gin c sn, chng hn khng th dng li khi mi truy nhp n l mt trng li l mt bin cu trc. (5)- Khi c nhiu trng ca mt bin cu trc cng c truy nhp th trnh vit di dng tn bin cu trc, ta c th nh ngha qua mt macro (t dng!): #define tn_macro tn_bin_cu_trc;

sau mt trng ca bin cu trc c th s dng thng qua quy tc: tn_macro.tn_trng (6) - Cc kiu cu trc cng c th khi u mt cch bnh thng, v d: struct address { char street[30]; unsinged int number; unsigned long phone; } A[] = { { thuy khue, 14, 7540199}, { hoang hoa tham, 174, 8949199}, { cat linh, 231, 8520009} }; Bi tp minh ha Vit chng trnh - Nhp l lch ca n sinh vin. (L lch sinh vin c m t v d 2) - In ln mn hnh danh sch cc sinh vin va nhp c sp xp theo chiu tng dn.
#include <stdio.h> #include <conio.h> #include <string.h> main() { typedef struct { unsigned int d,m,y; } date; typedef struct { char *street; unsigned int number; unsigned long phone; } address; struct sinhvien { char *ht; date ns; address dc; };

struct sinhvien sv[100]; int n; int i,j; struct sinhvien tg; printf("\n nhap so sinh vien: "); scanf("%d",&n); fflush(stdin); for(i=0;i<n;i++) { char tg[30]; unsigned int len; unsigned int d1,m1,y1; fflush(stdin); printf("\n sv[%d]:\n",i+1); printf("ho ten : "); gets(tg); len = strlen(tg); sv[i].ht = (char*) malloc (len+1); strcpy(sv[i].ht, tg); printf("ngay sinh: "); scanf("%d%d%d",&d1, &m1, &y1); sv[i].ns.d=d1; sv[i].ns.m=m1; sv[i].ns.y=y1; fflush(stdin); printf("dia chi:\n "); printf("ten pho: "); gets(tg); len=strlen(tg); sv[i].dc.street = (char*) malloc (len+1); strcpy(sv[i].dc.street, tg); printf("so nha: "); scanf("%d", &sv[i].dc.number); printf("so dien thoai: "); scanf("%d", &sv[i].dc.phone); } for(i=0;i<n-1;i++) for(j=i+1;j<n;j++) if (strcmp(sv[j].ht,sv[i].ht)<0) { tg=sv[i]; sv[i]=sv[j]; sv[j]=tg; } printf("\n danh sach sinh vien duoc sap xep theo ho ten:"); for(i=0;i<n;i++) { printf("\n %s : %d/%d/%d", sv[i].ht, sv[i].ns.d, sv[i].ns.m, sv[i].ns.y); printf("\n pho: %s, so nha: %d, dien thoai: %d", sv[i].dc.street, sv[i].dc.number, sv[i].dc.phone); }

getch(); }

Bi 2. CU TRC T TR V DANH SCH LIN KT

1. Con tr cu trc v a ch cu trc


C php v con tr v a ch - Bin con tr cu trc c khai bo nh sau: struct tn_kiu_cu_trc *tn_bin_con_tr; - Cng nh cc bin con tr khc , con tr cu trc c th s dng cha a ch ca bin kiu cu trc hoc xin cp pht b nh cho cc bin ng c kiu cu trc. Trng hp cp pht b nh ng to ra danh sch lin kt l mt vn quan trng ta s nghin cu mc 2. - V nguyn tc c php chung, con tr cu trc cng nh cc con tr kiu d liu khc. - V d struct hoadon { int sohd; char tenhang[30]; }; struct hoadon hd1, hd2, *p, *q, *r, ds[100]; trong khai bo trn ta c: . hd1, hd2 l tn cc bin cu trc kiu hoadon . *p, *q , *r l tn cc bin con tr c kiu hoadon . ds[100] l mt bin mng m cc phn t c kiu hoadon. - By gi ta c th vit cc lnh: p=&hd1; /* p cha a ch ca hd1 */ q=&ds[5]; /* p cha a ch ca ds[5] */ r=ds; /* r cha a ch ca ds[0] */ v khi *p == hd1

*q == ds[5] r[i] == ds[i] == *(r+i) - truy nhp ti mt trng ca bin cu trc ta c 2 cch: tn_con_tr -> tn_trng (*tn_con_tr).tn_trng Nh vy dng ton t -> khi v tri l con tr biu th a ch bin cu trc, dng ton t . khi v tri l con tr biu th gi tr bin cu trc. V d: p->sohd=24; hoc (*p).sohd=24; q->sohd=5; hoc (*q).sohd=5; (tc l ds[5].sohd = 5;) r[i].sohd=i; hoc (r+i)->sohd = i; hoc *(r+i).sohd = i; v a ch &ds[i].sohd == &p[i].sohd; - Trng hp con tr mng cu trc (nh v d trn) c th c cc php ton tng gim a ch con tr ch nh v tr ca cc phn t trong mng. V d Khi r =ds; Th (r+i) l a ch phn t th i &r[i].tn_trng l a ch ca trng ca phn t th i. *(r+i) l gi tr ca phn t th i (*(r+i)).tn_trng == r[i].tn_trng == (r+i)->tn_trng = ds[i].tn_trng : l gi tr ca trng ca phn t th i. Bi tp minh ha Vit chng trnh s dng con tr cu trc tr ti mng cc cu trc: - Nhp vo mt mng n mt hng: gm s ha n, tn hng - Sp xp danh sch cc mt hng theo chiu gim dn ca s ha n.
#include <stdio.h> #include <conio.h> #include <string.h> main() { struct mathang

{ unsigned int sohd; char tenh[30]; }; struct mathang *p, tg, ds[100]; int n; int i,j; p=ds; printf("\n nhap so mat hang: "); scanf("%d",&n); for(i=0;i<n;i++) { printf("\n mh[%d]:\n",i+1); printf("ten hang: "); fflush(stdin); gets((p+i)->tenh); printf("so hoa don: "); scanf("%d", &p[i].sohd); } for(i=0;i<n-1;i++) for(j=i+1;j<n;j++) if (p[j].sohd>p[i].sohd) {tg=p[i]; p[i]=p[j]; p[j]=tg;} printf("\n danh sach hang duoc sap xep giam theo so hoa don :\n"); for(i=0;i<n;i++) printf("%s %d , ", (*(p+i)).tenh, p[i].sohd); getch(); }

2. Truyn cu trc cho hm


2.1. Nguyn tc chung - i ca hm c th l: + Bin cu trc. Khi tham s thc s l mt gi tr cu trc (truyn kiu tham tr) + Con tr cu trc. Khi tham s thc s ca hm l a ch ca bin cu trc: . Trc tip dng bin vi a ch ca n. (nn dng cch ny nu khng c g c bit v vic phi x l gin tip mt bin cu trc.) . Hoc dng gin tip qua mt con tr thc s m trc gn bng a ch ca bin cu trc.

+ Mng cu trc hnh thc hoc con tr cu trc. Khi tham s thc tng ng l tn mng cu trc. - Hm c th tr v gi tr: + Gi tr cu trc. + Con tr cu trc. 2.2. V d Xt kiu cu trc nhanvien gm 3 thnh phn: + ht (h tn) kiu mng char + ns (ngy thng nm sinh) kiu struct date + bl (bc lng) kiu float Xy dng 6 hm sau y: + Hm 1: nhanvien *ptr_tim(char *ht, nhanvien h[], int n); c tc dng tm trong danh sch n nhn vin trong mng h ngi c tn cho trong ht. Hm tr v con tr tr vo nhn vin tm thy hoc tr vo null nu khng c nhn vin ny. + Hm 2: nhanvien struct_tim(char *ht, nhanvien h[], int n); cng c tc dng nh hm *ptr_tm nhng n tr v gi tr cu trc cha thng tin ca ngi tm c. Cc thng tin ny bng 0 nu khng tm thy. + Hm 3: void hoanvi(nhanvien *p, nhanvien *q); hon v 2 cu trc + Hm 4: void sapxep_ns(nhanvien *p, int n); sp xp mt mng cc cu trc tng dn theo trng nm sinh. Mng c xc nh bi con tr p. + Hm 5: void nhap_nv(nhanvien *p); nhp t bn phm thng tin cho mt nhn vin , nhn vin ny c xc nh bi con tr p.

+ Hm 6: void in_nv(nhanvien nv); in ra thngtin ca mt nhn vin. Chng trnh vn dng cc hm trn : - Nhp danh sch n nhn vin. - Sp xp danh sch cc nhn vin theo nm sinh tng dn. - In danh sch nhn vin sau khi sp xp. - Hai cch tm kim mt nhn vin ( dng hm ptr_tim v struct_tim)
#include <stdio.h> #include <conio.h> #include <string.h> struct date {int d,m,y;}; typedef struct { char ht[30]; struct date ns; float bl; } nhanvien; void nhap_nv(nhanvien *p) { nhanvien nvtg; printf("\n ho ten: "); fflush(stdin); gets(nvtg.ht); printf(" ngay thang nam sinh: "); scanf("%d%d%d%*c",&nvtg.ns.d,&nvtg.ns.m,&nvtg.ns.y); printf(" bac luong: "); scanf("%f%*c",&nvtg.bl); *p=nvtg; } void in_nv(nhanvien nv) { printf("\n %s: %d/%d/%d , bac luong: %0.1f", nv.ht, nv.ns.d, nv.ns.m, nv.ns.y, nv.bl); } void hoanvi(nhanvien *p,nhanvien *q) { nhanvien nvtg; nvtg=*p; *p=*q; *q=nvtg; } void sapxep_ns(nhanvien *p, int n) { int i,j; for(i=0;i<n-1;i++) for(j=i+1;j<n;j++)

if(p[j].ns.y < p[i].ns.y) hoanvi(&p[i],(p+j)); } nhanvien* ptr_tim(char *s, nhanvien h[], int n) {int i; for(i=0;i<n;i++) if (strcmp(s,h[i].ht)==0) return (&h[i]); return (NULL); } nhanvien struct_tim(char *s, nhanvien h[], int n) { int i; nhanvien nvtg; nvtg.ns.d=nvtg.ns.m=nvtg.ns.y=0; nvtg.bl=0.0; nvtg.ht[0]=0; for(i=0;i<n;i++) if(strcmp(s,h[i].ht)==0) return (h[i]); return (nvtg); } main() { nhanvien *p, ds[100]; int n; char s[30]; int i,j; clrscr(); printf("\n nhap so nhan vien: "); scanf("%d",&n); for(i=0;i<n;i++) { printf("\n nhap nhan vien thu %d :\n",i+1); nhap_nv(&ds[i]); } sapxep_ns(ds,n); printf("\n danh sach sau khi sap xep tang theo nam sinh la:\n"); for(i=0;i<n;i++) in_nv(ds[i]); while(1) { printf("\n nhap ho ten sinh vien can tim (cach 1) : "); fflush(stdin); gets(s); if(s[0]==0) break;

if((p=ptr_tim(s,ds,n))==NULL) printf("\n khong co sinh vien nay."); else { printf("\n tim thay cach 1 : "); in_nv(*p) ; } } while(1) { printf("\n nhap ho ten sinh vien can tim (cach 2) : "); fflush(stdin); gets(s); if(s[0]==0) break; if(struct_tim(s,ds,n).ht[0]==0) printf("\n khong co sinh vien nay."); else { printf("\n tim thay cach 2: "); in_nv( struct_tim(s,ds,n) ) ; } } printf("\n bam enter de ket thuc chuong trinh"); getch(); }

3. Cu trc t tr v danh sch lin kt


3.1. Khai bo cu trc t tr - Mt kiu cu trc m trong c mt trng l mt con tr c kiu d liu l chnh kiu cu trc th gi l cu trc t tr. - Mt cch hnh thc nu x l mt cu trc c kiu T th trong x c mt trng l con tr *f c kiu l T. - Bn ghi t tr dng xy dng danh sch lin kt-mt cu trc d liu c nhiu ng dng thc t. Cch 1 typedef struct T { kiu_d_liu tn_trng; ... struct T *f; } x; Cch 2 struct T { kiu_d_liu tn_trng;

... struct T *f; } x; Cch 3 typedef struct T x { kiu_d_liu tn_trng; x *f; }; 3.2. Cc php ton trn danh sch lin kt Xt mt danh sch lin kt to bi cc cu trc t tr m mi mt nt lu tr thng tin ca mt cn b , gi s gm 2 mc thng tin l h tn v nm sinh. V, ng nhin mi mt nt c thm mt trng l con tr *next c kh nng tr vo cc nt k trong danh sch, do *next c kiu d liu l chnh kiu ca nt. Cc mc di y s th hin cch ci t danh sch lin kt v cc php ton c bn trn danh sch lin kt Danh sch lin kt di y d nh t chc kiu danh sch lin kt ngc. Ngha l nt sau s tr vo nt trc. Danh sch s c qun l bi con tr last tr vo nt cui cng trong danh sch.
last nt 3 nt 2 nt 1 NULL

nh ngha cu trc t tr typedef struct node { char ht[30]; unsigned int ns; struct node *next; } canbo; canbo *last; Khi to danh sch lin kt ngc (nt sau tr vo nt trc)

last =NULL; B sung mt mc d liu vo cui danh sch - To mt nt mi


canbo *p; int t; p=(canbo*) malloc (sizeof(canbo)); p->next=NULL; printf("\n nhap can bo thu %d\n",++i); printf("ho ten: "); fflush(stdin); gets(p->ht); if(p->ht[0]==0) break; printf("nam sinh: "); scanf("%d",&t); p->ns=t;

- Thm p vo danh sch


if(last==NULL) last=p; else { p->next=last; last=p; }

In danh sch ln mn hnh


p=last; while(p!=NULL) {printf("\n %s %d", (*p).ht,(*p).ns); p=p->next;

} Tm kim mt mc d liu trn danh sch


printf("\n nhap ho ten mot can bo can tim: "); fflush(stdin); gets(s); found=0; p=last; while(!found && p!=NULL) {if(strcmp(s,p->ht)==0) {found=1;break;} else p=p->next; } if(found) printf("\n co can bo do trong danh sach"); else printf("\n khong co can bo trong danh sach");

Xa mt mc d liu ra khi danh sch

printf("\n nhap ho ten mot can bo can xoa: "); fflush(stdin); gets(s); found=0; p=last; q=NULL; while(!found && p!=NULL) { if(strcmp(s,p->ht)==0) found=1; else {q=p; p=p->next;} } if(found) { if(q==NULL) {last=last->next;} else {q->next=p->next; free(p);} }

Chn mt mc d liu vo trc mt mc d liu no trong danh sch


printf("\n nhap thong tin mot can bo can chen:\n "); r=(canbo*) malloc (sizeof(canbo)); r->next=NULL; printf("ho ten: "); fflush(stdin); gets(r->ht); printf("nam sinh: "); scanf("%d",&t); r->ns=t; printf("\n Can chen vao truoc can bo co ten la gi "); printf("(tinh tu can bo cuoi nguoc ve dau danh sach): "); fflush(stdin); gets(s); found=0; p=last; q=NULL; while(!found && p!=NULL) { if(strcmp(s,p->ht)==0) found=1; else {q=p; p=p->next;} } if(found) { if(q==NULL) {r->next=last; last=r;} else {q->next=r; r->next=p;} }

4. Cc phng php ci t cc php ton Vic t chc chng trnh ci t cc php ton trn danh sch lin kt c th c 3 cch thc hin: - Cch 1: Chng trnh khng t chc cc hm (pheptoan1.c). Cch t chc ny u im l d thc hin, nhng nhc im rt ln l chng trnh s di, cng knh, khng tin li khi mt php ton (chng hn nh php tm kim) phi vn dng nhiu ln.

- Cch 2: Chng trnh t chc thnh cc hm, trong mi hm m nhn mt php ton (pheptoan2.c). Cch t chc ny khc phc nhc im ca cch thc nht, nhng c nhc im l s kh hn , nht l vic truyn vo hm cc i l cc con tr cu trc. - Cch 3: (pheptoan3.c- mc 4) Ging nh cch th 3, nhng y s s dng ti k thut ci t con tr tr ti mt con tr khc, tc l con tr ca con tr. Pheptoan1.C
#include <stdio.h> #include <conio.h> #include <string.h> void main(){ typedef struct node { char ht[30]; unsigned int ns; struct node *next; } canbo; canbo *last; canbo *p; int i,t; char s[30]; int found; canbo *q; canbo *r; /*------------------------------------*/ /* tao danh sach can bo */ /*------------------------------------*/ last=NULL; i=0; while(1) { p=(canbo*) malloc (sizeof(canbo)); p->next=NULL; printf("\n nhap can bo thu %d\n",++i); printf("ho ten: "); fflush(stdin); gets(p->ht); if(p->ht[0]==0) break; printf("nam sinh: "); scanf("%d",&t); p->ns=t; if(last==NULL) last=p; else { p->next=last;

last=p; } } /*------------------------------------*/ /* in danh sach */ /*------------------------------------*/ p=last; while(p!=NULL) {printf("\n %s %d", (*p).ht,(*p).ns); p=p->next; } /*-----------------------------------------------*/ /* tim kiem tren danh sach theo ten */ /*-----------------------------------------------*/ while(1) { printf("\n nhap ho ten mot can bo can tim: "); fflush(stdin); gets(s); if(s[0]==0) break; found=0; p=last; while(!found && p!=NULL) {if(strcmp(s,p->ht)==0) {found=1;break;} else p=p->next; } if(found) printf("\n co can bo do trong danh sach"); else printf("\n khong co can bo trong danh sach"); } /*-----------------------------------------------*/ /* xoa mot can bo khoi danh sach */ /*-----------------------------------------------*/ printf("\n nhap ho ten mot can bo can xoa: "); fflush(stdin); gets(s); found=0; p=last; q=NULL; while(!found && p!=NULL) { if(strcmp(s,p->ht)==0) found=1; else {q=p; p=p->next;} } if(found) { if(q==NULL) {last=last->next;} else {q->next=p->next; free(p);} printf("\n can bo do da duoc xoa");

p=last; while(p!=NULL) {printf("\n %s %d", (*p).ht,(*p).ns); p=p->next; } } else printf("\n khong co can bo trong danh sach");

/*----------------------------------------------------*/ /* chen mot can bo vao giua danh sach */ /*----------------------------------------------------*/ printf("\n nhap thong tin mot can bo can chen:\n "); r=(canbo*) malloc (sizeof(canbo)); r->next=NULL; printf("ho ten: "); fflush(stdin); gets(r->ht); if(r->ht[0]==0) goto end; printf("nam sinh: "); scanf("%d",&t); r->ns=t; printf("\n Can chen vao truoc can bo co ten la gi "); printf("(tinh tu can bo cuoi nguoc ve dau danh sach): "); fflush(stdin); gets(s); if(s[0]==0) goto end; found=0; p=last; q=NULL; while(!found && p!=NULL) { if(strcmp(s,p->ht)==0) found=1; else {q=p; p=p->next;} } if(found) { if(q==NULL) {r->next=last; last=r;} else {q->next=r; r->next=p;} printf("\n can bo do da chen"); p=last; while(p!=NULL) {printf("\n %s %d", (*p).ht,(*p).ns); p=p->next; } } else printf("\n khong co can bo trong danh sach"); end: printf("\n bam enter de ket thuc chuong trinh."); getch();

Pheptoan2.C
#include <stdio.h> #include <conio.h> #include <string.h>

typedef struct node { char ht[30]; unsigned int ns; struct node *next; } canbo; canbo *last; /*---------------------------------------------*/ /* ham nhap du lieu cho mot nut */ /*--------------------------------------------*/ void nhapmotcb(canbo *p) { unsigned int t; printf("ho ten: "); fflush(stdin); gets(p->ht); if(p->ht[0]!=0) {printf("nam sinh: "); scanf("%d",&t); p->ns=t;} } /*------------------------------------------------------------*/ /* ham ket nap mot nut moi vao cuoi danh sach*/ /*-------------------------------------------------------------*/ void bosung_ds(canbo *p) { if(last==NULL) last=p; else {p->next=last;last=p;} } /*--------------------------------------------------------*/ /* ham in mot can bo va danh sach can bo */ /*--------------------------------------------------------*/ void in_cb(canbo *p) {printf("\n %s %d", (*p).ht,(*p).ns); } void in_ds(canbo *last) { canbo *p; p=last;

while(p!=NULL) {in_cb(p); p=p->next;} } /*------------------------------------------------------------*/ /* ham tim kiem mot can bo */ /* ket qua tra lai la con tro tro vao nut tim thay */ /*------------------------------------------------------------*/ canbo* timkiem(canbo *last,char s[]) /* tra lai con tro q tro vao nut tim thay. q=NULL neu khong co*/ { canbo *p; p=last; while(p!=NULL) {if(strcmp(s,p->ht)==0) {return(p);} else p=p->next; } return (NULL); } /*-----------------------------------------------------------------------*/ /* ham tim kiem mot can bo */ /* ket qua tra lai la con tro tro vao cha cua nut tim thay */ /*-----------------------------------------------------------------------*/ canbo* timkiem2(canbo *last, char s[]) /* tra lai con tro p tro vao cha cua nut tim thay. p=NULL neu nut tim thay la last */ { canbo *p,*q; q=last;p=NULL; while(q!=NULL) { if(strcmp(s,q->ht)==0) break; p=q; q=q->next; } return (p); } /*------------------------------------------------------------------*/ /* ham xoa mot nut co biet truoc mot muc du lieu */ /*------------------------------------------------------------------*/ void xoa_cb(char s[]) { canbo *p,*q; q=timkiem(last,s); p=timkiem2(last,s); if(q==NULL) printf("\n khong thay can bo nay.");

else { if(p==NULL) {last=last->next;} else {p->next=q->next; free(q);} printf("\n can bo do da duoc xoa"); in_ds(last); } } /*-----------------------------------------------------------------*/ /* ham chen mot nut moi truoc mot nut nao do */ /*-----------------------------------------------------------------*/ void chen_cb(canbo *r,char s[]) { canbo *p,*q; q=timkiem(last,s); p=timkiem2(last,s); if(q==NULL) printf("\nkhong thay can bo %s",s); else { if(p==NULL) {r->next=last; last=r;} else {p->next=r; r->next=q;} printf("\n da chen xong can bo do"); in_ds(last); } } /*------------------------------------*/ /* chuong trinh chinh */ /*------------------------------------*/ void main(){ int i=0; canbo *p, *q, *r; char s[30]; last=NULL; while(1) { printf("\n nhap can bo thu %d: \n",++i); p=(canbo*) malloc (sizeof(canbo)); p->next=NULL; nhapmotcb(p); if (p->ht[0]==0) break; bosung_ds(p); } in_ds(last);

while(1) { printf("\n nhap ho ten mot can bo can tim: "); fflush(stdin); gets(s); if(s[0]==0) break; p=timkiem(last,s); if(p==NULL) printf("\n khong co can bo do."); else in_cb(p); } printf("\n nhap ho ten mot can bo can xoa: "); fflush(stdin); gets(s); if(s[0]!=0) xoa_cb(s); printf("\n nhap thong tin mot can bo can chen:\n "); r=(canbo*) malloc (sizeof(canbo)); r->next=NULL; nhapmotcb(r); if(r==NULL) goto end; printf("\n Tinh tu can bo cuoi nguoc ve dau danh sach"); printf("\n Can chen vao truoc can bo co ten la gi: "); fflush(stdin); gets(s); if(s[0]==0) goto end; chen_cb(r,s); end: printf("\n bam enter de ket thuc chuong trinh."); getch(); }

5. Con tr ca con tr cu trc t tr Nhn xt Trong chng trnh 3.3.2 (pheptoan2.c) ta thy c mt vi im hi khng bnh thng, ng ra l hi bt tin. - Th nht l con tr last c c tnh l bin ton cc cc hm thao tc trn bin ton cc ny. Chng hn vic nhp vo thm, xa i hay hy b mt nt trong danh sch ng nhin lm cho danh sch thay i , ngha l con tr last (dng xc nh ton danh sch) s thay i theo. Nhng iu ny ta khng cn lo lng v last l bin ton cc ri. - Th hai l tt c cc hm c nh lm thay i gi tr ca mt con tr cu trc t tr no u khng truyn thnh i ca hm. C ngha l c vn xy ra khi nh truyn mt con tr cu trc t tr trong hm nh mt tham s bin (bi v lc ny chng u b coi l tham s gi tr). V d 1:

Nu hm void bosung_ds(canbo *p) sa thnh void bosung_ds(canbo *last, canbo *p) th vic kt np thm mt nt p vo last ch c tc dng trong thn hm. Khi hm kt thc, last coi nh khng c thm p. V, nh vy on trnh trong main to danh sch l khng c tc dng. V d 2: Cng t sinh ra chuyn phi vit ring r 2 hm tm kim v bn thn 2 hm tm kim cng lng trnh vic tr li kt qu tm kim nh mt i l con tr no m li nh chnh bn thn tn hm. ng l ra 2 hm tm kim phi thay bng mt hm: void timkiem(canbo *last,char s[], canbo *p, canbo *q); ngha l tm cn b tn trong s ca danh sch last. Nu tm thy th q tr vo nt c tn cn b ny cn p th tr vo cha ca nt ... Nhng vit nh trn th *p, *q u c coi ch l cc tham s gi tr, trong thn hm du cho p v q lm c iu th ra khi hm, p v q vn khng xc nh. V d 3: Xt hm nhp cn b:
void nhapmotcb(canbo *p)

thc cht ch l vic nhp d liu n thun cho bin ng tr bi p v bin ng ny phi c cp pht ngoi main(), nu cp pht trong hm th kt qu chng trnh khng cn ng na! Con tr ca con tr - Khi nim v con tr ca con tr s khc phc cc bt tin trn. - mt con tr cu trc t tr truyn vo hm vi t cch nh mt tham s bin, ngha l gi tr ca n k c vic cp pht b nh c thn hm lm thay i s c gi li khi ra khi hm th con tr phi c khai bo l con tr ca con tr. Trong trng hp ny l con tr ca con tr cu trc t tr. - Mt chng trnh s dng cc php ton ci t bng hm vi i l con tr ca con tr cu trc t tr s cho cm gic t nhin v d chu hn rt nhiu v tnh tin li ca n.

kiu_hm tn_hm ( kiu_cu_trc_t_tr { /* thn hm s dng :*/ *tn_bin_con_tr } Khi gi hm tn_hm(&tn_bin_con_tr)

** tn_bin_con_tr)

V d 1 : hm nhp cn b v hm b sung cn b c th chuyn thnh


int nhapmotcb(canbo **p) { unsigned int t; (*p)=(canbo*) malloc (sizeof(canbo)); (*p)->next=NULL; printf("ho ten: "); fflush(stdin); gets((*p)->ht); if((*p)->ht[0]==0) return(0); else {printf("nam sinh: "); scanf("%d",&t); (*p)->ns=t;} return(1); } void bosung_ds(canbo **start,canbo *p) { canbo *q; if(*start==NULL) *start=p; else { q=*start; while(q->next!=NULL) q=q->next; q->next=p;} }

Vy khi on trnh trong main s to danh sch lin kt (thun) nh sau:


start=NULL; while(1) { printf("\n nhap can bo thu %d: \n",++i); if(nhapmotcb(&p)==0) break; bosung_ds(&start,p); }

Pheptoan3.C Xy dng mt danh sch lin kt thun cng vi cc php ton c bn ca mt danh sch lin kt.
Start nt 1 nt 2 nt 3 NULL

#include <stdio.h> #include <conio.h>

#include <string.h> typedef struct node { char ht[30]; unsigned int ns; struct node *next; } canbo; canbo *start; /*---------------------------------------*/ /* nhap du lieu cho mot nut */ /*--------------------------------------*/ int nhapmotcb(canbo **p) { unsigned int t; (*p)=(canbo*) malloc (sizeof(canbo)); (*p)->next=NULL; printf("ho ten: "); fflush(stdin); gets((*p)->ht); if((*p)->ht[0]==0) return(0); else {printf("nam sinh: "); scanf("%d",&t); (*p)->ns=t;} return(1); } /*-----------------------------------------------------*/ /*ket nap mot nut moi vao cuoi danh sach*/ /*----------------------------------------------------*/ void bosung(canbo **start,canbo *p) { canbo *q; if(*start==NULL) *start=p; else { q=*start; while(q->next!=NULL) q=q->next; q->next=p;} } /*---------------------------------------------------*/ /* in mot can bo va danh sach can bo */ /*---------------------------------------------------*/ void in_cb(canbo *p) {printf("\n %s %d", (*p).ht,(*p).ns); } void in_ds(canbo *start) { canbo *p; p=start; while(p!=NULL) {in_cb(p); p=p->next;} } /*------------------------------------------------------------------------*/ /* tim kiem mot can bo co ten chua trong mang ky tu s */ /* neu khong tim thay thi ham tra gia tri 0 */ /* neu tim thay: */ /* - ham tra gia tri 1 */ /* - *q tro vao nut tim thay */

/* - *p tro vao cha cua *q */ /* - neu *q tro vao nut start thi ham tra gia tri 2 */ /*-------------------------------------------------------------------------*/ int timkiem(canbo *start,char s[],canbo **p, canbo **q) { *q=start; while(*q!=NULL) { if(strcmp(s,(*q)->ht)==0) {if(*q==start) return 2; else return 1;} else {*p=*q; *q=(*q)->next; } } return 0; } /*----------------------------------------------------------------------*/ /* xoa mot can bo co ten chua trong mang ky tu s */ /*---------------------------------------------------------------------*/ void xoacanbo(canbo **start,char s[]) {canbo *p,*q; int k=timkiem(*start,s,&p,&q); if(k==0) {printf("khong co can bo %s ",s); return;} if(k==2) (*start)=(*start)->next; if(k==1) p->next=q->next; free(q); } /*--------------------------------------------------------------------------*/ /* Chen mot can bo co ten chua trong nut r */ /* vao sau mot can bo trong danh sach ma can bo nay */ /* co ten chua trong mang ky tu s. */ /*-------------------------------------------------------------------------*/ void chencanbo(canbo **start,canbo *r,char s[]) { canbo *p,*q; if(timkiem(*start,s,&p,&q)==0) {printf("khong co can bo %s ",s); return;} r->next=q->next; q->next=r; } /*=============================*/ /* chuong trinh chinh */ /*=============================*/ void main(){ int i=0; canbo *p, *q, *r; char s[30]; start=NULL; while(1) { printf("\n nhap can bo thu %d: \n",++i); if(nhapmotcb(&p)==0) break; bosung(&start,p); }

in_ds(start); while(1) { printf("\n nhap ho ten mot can bo can tim: "); fflush(stdin); gets(s); if(s[0]==0) break; if(timkiem(start,s,&p,&q)==0) printf("\n khong co can bo do."); else { printf("\n tim thay can bo do."); in_cb(q); } } printf("\n nhap ho ten mot can bo can xoa: "); fflush(stdin); gets(s); xoacanbo(&start,s); in_ds(start); printf("\n nhap thong tin mot can bo can chen:\n "); if(nhapmotcb(&r)==0) goto end; printf("\n Can chen vao sau can bo co ten la gi: "); fflush(stdin); gets(s); if(s[0]==0) goto end; chencanbo(&start,r,s); in_ds(start); end: printf("\n bam enter de ket thuc chuong trinh."); getch(); }

Bi 3. KIU D LIU HP - UNION

1. Cu trc kiu bit


- Mt cu trc c bit gi l cu trc bit v cc trng ca n c quy nh c th l chim bao nhiu bit trong b nh, d trng c kiu l int, char, unsigned. - n v cp pht nh nht cho cu trc l 2B (tc l 16bit) v c tip tc tng 2B mt nh th. Chng hn mt cu trc gm cc trng m tng cng chim 5 bit th cu trc vn c cp pht 16 bit (ngha l tha 11bit), nu tng cng cc trng chim 20 bt th cu trc vn c cp pht 32bit (ngha l tha ra 10 bit). - Cc trng vi s bt ca chng theo th t khai bo s chim cc bt trong cc t my (2B) tng ng theo th t t phi sang tri, ngha l t byte thp n byte cao. - Khai bo cu trc ny nh sau: struct tn_kiu_cu_trc { kiu_d_liu1 tn_trng1 : s_bt; kiu_d_liu2 tn_trng2 : s_bt;

...} [tn_bin_cu_trc]; V d: struct date { unsigned ngay : 5; /* chim 5 bt, s ln nht l 31 */ unsigned thang : 4; /* chim 4 bt, s ln nht l 16 */ int : 2; /* chim 2 bt, b trng unsigned nam : 5 ; /* chim 5 bt, s ln nht l 31 (quy c l 2031) */ } d; Trong b nh, chui cc bt cho cc trng ca cu trc d nh sau: byte cao nm thng byte thp ngy

Mt s quy nh i vi cc trng kiu bit: . Mt trng nu c quy nh s bit, phi c kiu int (gi l trng kiu bit) . di ca mi trng kiu bit di khng qu 2B . Khi mun b qua mt s bit, ta khng vit tn trng. . Khng cho php ly a ch ca trng kiu bit . Khng xy dng cc mng kiu trng kiu bit . Khng xy dng hm tr v mt thnh phn kiu trng kiu bit, c th dng mo, chng hn nu t l mt trng kiu bit ca cu trc x th: int k = x.t; return k; * ng dng ca cu kiu bit l tit kim b nh v kt hp vi kiu d liu union ly ra cc bit ca mt t.

2. Kiu union
2.1. Nhn xt - Vic nh ngha mt bin kiu union , vic khai bo mt bin kiu union, mng union, con tr union cng ging nh cu trc. Vic truy nhp n cc thnh phn kiu union cng ging nh truy nhp n cc thnh phn ca cu trc. Thnh

phn ca cu trc c th c kiu union v ngc li, thnh phn ca union c th c kiu cu trc. (Trong c php, t kha struct tng ng s thay bng t kha union) - Cng ging nh struct, union cng gm nhiu thnh phn, nhng chng khc nhau ch, cc thnh phn ca cu trc thng c nhng vng nh khc nhau, cn cc thnh phn ca union c cp pht mt vng nh chung. di ca union bng di ca thnh phn ln nht. V d typedef union { unsigned int n; /*chim 2B */ float r; /*chim 4B */ unsigned char s[2]; /*chim 2B */ } U; Vy U chim 4B, trong n,r, s u dng chung 4 B, ngha l: r chim 4B, n chim 2B u tin, s[2] cng chim 2B u tin Nu ta gn: U.n=0xa1b2; th do n v s[2] cng chim 2 byte u tin nn U.s[1]=0xa1, U.s[2]=0xb2. 2.2. Ly ra cc bit ca cc trng Cu trc kiu bit thng c s dng trong kiu union ly ra cc bye v cc bit ca cc s nguyn. V d
#include <stdio.h> #include <conio.h> #include <string.h> #include <dos.h> void main(){ struct date{ unsigned ngay:5; unsigned thang:4; unsigned nam:7; }; union { struct {unsigned a; } A;

struct { unsigned bit0:1; unsigned bit1:1; unsigned bit2:1; unsigned bit3:1; unsigned :4; unsigned :7; unsigned bit15:1; } B; }U; U.A.a=11; printf("\n%d %d%d%d%d",U.B.bit7, U.B.bit3,U.B.bit2,U.B.bit1,U.B.bit0); printf("\n bam enter de ket thuc chuong trinh."); getch(); }

Nu khi chy chng trnh, kt qu l 0 1001 Gii thch union U chim 2 B v cc thnh phn U.A v U.B u chung nhau 2B ny. Cho nn khi U.A.a=11; (tc l ni dung ca nh 2B ny l 0000.1001) th cc trng kiu bit ca cu trc B (nh ni trong mc 1) s ln lt chim cc bit t phi sang tri ca 2B . Cc bt sau 0,1,2,3 c gn tng cho cc trng c tn l bit0, bit1,bit2,bit3. Chng s ln lt nhn gi tr ca 4 bit u tin ca nh 2B tc l 1001. 4 bt tip theo ca bye thp v 7 bt na tip theo ca byte cao b b qua khng dng. Cn 1 bit th 16 cui cng th trng c tn bit15 s nhn gi tr ca bit th 15 trong s nguyn 11 , ngha bit15=0. 2.3. Thng tin h thng ti a ch 410H Ti a ch 410H di 2 byte , theo th t cc bit t byte thp n byte cao gm cc thit b sau y: - Bit 0: Cho bit c a mm (1) hay khng (0) - Bit 1: C b ng x l ton hc (1) hay khng (0) - Bit 2,3: S lng RAM trn mother board: 00: 16K, 01:32K, 10:48K, 11:64K. Trong my AT hai bit ny khng c dng n. - Bit 4,5: Cho bit kiu mn hnh ang dng: 01:PCjr mu 40 ct, 10: mu 80 ct, 11: n sc 80 ct, 00: khng r kiu mn hnh.

- Bit 6,7: Cho bit s lng a mm (tr i 1) (ngha l lc in ra gi tr ca 2 bt ny phi cng thm 1) - Bt 8: C lp chip DMA (0) hay khng lp (1) - Bt 9,10,11: Cho bit s cc cng ni tip RS232 - Bit 12: My c cm b phi ghp tr chi (1) hay khng (0) - Bit 13: My in c cm cng ni tip (1) hay khng (0). Bit ny khng s dng i vi my PC. - Bt 14,15 : S my in c cm vo my tnh. Vy xem cc thng tin trn ta c th s dng struct v union ly ra gi tr cc bit v in ln mn hnh.
#include #include #include #include <stdio.h> <conio.h> <string.h> <dos.h>

char *MaHieu(); typedef struct { unsigned FloppyDisk :1; /* Co it nhat 1 o dia mem =1*/ unsigned Coprocessor:1; /* Co bo dong xu ly toan hoc=1 */ unsigned RAM :2; /* So luong RAM tren mainboard */ unsigned Monitor :2; /* Kieu man hinh */ unsigned NFloppyDisk :2; /* So luong o mem */ unsigned DMA :1; /* Co lap chip DMA (0) */ unsigned NRS232 :3; /* So cac cong noi tiep RS232 */ unsigned Joystic :1; /* Co lap bo phoi ghep tro choi (1) */ unsigned SerialPrt :1; /* Co cam may in noi tiep khong */ unsigned NPrinter :1; /* So may in duoc cam */ } devices ; devices far *list = (devices far*) MK_FP (0, 0x410); void display(){ if(list->FloppyDisk) printf("\n Co it nhat mot o dia mem."); if(list->Coprocessor) printf("\n Co bo dong xu ly toan hoc."); if(strcmp("AT",MaHieu())) printf("\n Co %dK tren main board ",16 << list->RAM); printf("\n Kieu man hinh: "); switch (list->Monitor) { case 0: printf("Khong ro kieu man hinh."); break; case 1: printf("PCjt mau 40 cot."); break; case 2: printf("80 cot mau."); break; case 3: printf("Don sac 80 cot."); break; } printf("\n so o dia mem: %d.",list->NFloppyDisk+1);

if(!list->DMA) printf("\n Co chip DMA."); printf("\n So cong noi tiep: %d.",list->NRS232); if(list->Joystic) printf("\n Co bo phoi ghep tro choi."); if(list->SerialPrt) printf("\n Co may in noi tiep."); printf("\n So cong may in: %d.",list->NPrinter); } char *MaHieu(){ char far *MaHieu = (char far *) MK_FP (0xF000, 0xFFFE); char *s= (char*) malloc (15); unsigned char m = *MaHieu; switch (m){ case 0xFF: strcpy(s,"PC IBM"); break; case 0xFE: strcpy(s,"XT/PC portable"); break; case 0xFD: strcpy(s,"PCjr"); break; case 0xFC: strcpy(s,"AT"); break; case 0x2D: strcpy(s,"Compaq"); break; case 0x9A: strcpy(s,"Compaq Plus"); break; } return s; } void main() { clrscr(); display(); printf("\n Bam phim bat ky de ket thuc chuong trinh."); getch(); }

Chng 6. D LIU KIU TP - FILE


Bi 1. TP V CC HM CP 1

1. Tng quan so snh v tp nh phn v tp vn bn.


- Mt tp lu trn a c bn cht l mt dy cc byte c gi tr t 0..255. Cng v l do khi gp mt byte -1 th C ly lm du hiu kt thc tp. M EOF c gi tr -1. - C qun l 2 loi tp: tp nh phn v tp vn bn. + Tp kiu nh phn ghi v c trung thnh mi k t trn tp. Vic ghi tp c thc hin ghi theo cc byte nh phn nh trong b nh. Vic c tp dng li khi c xong k t m EOF. Tp kiu nh phn khng tng thch vi cu trc ca DOS. + Tp vn bn khc tp vn bn khi x l n k t LF (m 10) v k t m 26. C th l, khi ghi: mt k t LF s chuyn thnh cp k t (CR,LF) = (13,10) ghi chng vo tp. Khi c, gp cp k t (CR,LF) th k t CR c loi b v ta ch nhn c mt k t LF. Tp vn bn (khi c) nhn ra k t kt thc tp l EOF (-1) hoc m 26. iu ny ph hp vi cc tp vn bn chun , ngha l ph hp vi cu trc ca DOS , v DOS s dng k t m 26 lm k t kt thc tp. V d: Minh ha vic chuyn k t 10 thnh (13,10) khi ghi vo tp vn bn.
#include <stdio.h> #include <conio.h> main() { FILE *fvb, *fnp, *f; /* mo cac tep van ban va tep nhi phan de ghi */ fvb=fopen("vb.txt","wt"); fnp=fopen("np.bin","wb"); f=fopen("vd.txt","wt"); /*ghi cac ky tu len tep van ban fvb */
fputc('A',fvb); fputc(26,fvb); fputc(10,fvb); fputc('B',fvb);

/*ghi cac ky tu len tep nhi phan fnp */


fputc('A',fnp); fputc(26,fnp); fputc(10,fnp); fputc('B',fnp);

/*ghi 3 dong len tep van ban*/ fprintf(f,"%2d\n%2d\n%2d",56,7,8); /* Dong cac tep*/ fclose(fvb); fclose(fnp); fclose(f); printf("\n Da ghi xong."); getch(); }

Kt qu: Tp vb.txt nhn c chui 5 k t c m : 65 A 26 26 13 10 CR,LF 66 B

Tp np.txt nhn c chui 4 k t c m : 65 A 26 26 10 LF 66 B

Tp vn bn vd.txt nhn c mt chui 10 k t c m sau y: 53 s 5 54 s 6 13 10 CR,LF 32 space 55 s 7 13 10 CR,LF 32 space 56 s 8

Nhng nu thay lnh: f=fopen(vd.txt, wt) bng lnh: f=fopen(vd.txt, wb) th kt qu tp nh f s nhn c 8 k t c m sau y: 53 s 5 54 s 6 13 LF 32 space 55 s 7 10 LF 32 space 56 s 8

Cu trc ghi trong tp nh phn f khng cho php lnh Type ca DOS hin th 3 dng nh mong mun.

2. Cc k t m tp
Trong hm fopen c 2 i - i th nht l tn tp - i th hai gm 2 k t (gi chung l kiu): . K t u quy nh kiu m tp: m ghi (w), c (r), hay b sung vo cui tp (a). . K t th hai quy nh loi tp: tp vn bn (t) hay tp nh phn (b) - Ni ring, nu c du + xen gia 2 k t th c th va ghi va c, nu bt u l r+t hoc r+b th vic ghi c c kim tra li tn ti tp , nu bt u l w+t hoc w+b th khng kim tra li tn ti tp (tp khng c trn a s t ng c to mi). Nu trong 2 k hiu, ch vit k hiu u th ngm nh l tp vn bn. Tm li ta c th c: tp vn bn r hoc rt w hoc wt a hoc at r+ hoc r+t w+ hoc w+t a+ hoc a+t tp nh phn rb wb ab r+b w+t a+b

Tng quan v cc hm cp 1 v cc hm cp 2
- Thao tc vi tp bao gm cc cng vic: m tp; c d liu t tp chuyn ra bin; x l trn bin gii bi ton; kt qu x l li c th ghi vo tp; cui cng ng tp. Thao tc trn tp c thc hin bi 2 nhm hm: + Nhm hm cp 1: l cc hm c/ghi h thng thc hin vic c ghi nh DOS. c im ca cc hm ny l: . Khng c ghi theo tng kiu d liu m ch c c ghi tng dy byte, bao gm cc dch v c/ghi 2 byte i vi mi s nguyn, c/ghi 4 byte i vi mi s thc. . Mi tp c mt s hiu (gi l th - handle) v cc hm lm vic vi tp thng quan s hiu tp (l cc s nguyn)

+ Nhm hm cp 2: c xy dng t cc hm cp 1, d s dng v c nhiu kh nng hn: . C dch v c ghi tng kiu d liu. . C mt bin con tr tp xc nh cc tp. . S dng vng m trung gian trong qu trnh c/ghi tng tc truy xut d liu.

3. Thao tc vi tp (gii thiu cc hm cp 2)


Bao gm th t cc cng vic trong bi ton: - M tp - c/ghi d liu vi bin b nh - X l d liu trn bin - ng tp 3.1. M tp FILE *fopen(const char *tn_tp, const char *kiu); hm cho gi tr NULL nu m tp khng thnh cng. 3.2. c v ghi tp - Cc hm k t: + Ghi: int putc(inc c, FILE *f); int fputc(int c, FILE *f); + c: int getc(FILE *f); int fgetc(FILE *f); - Cc hm chui k t (thch hp vi tp vn bn) + Ghi: (tr v EOF khi li) int fputs(const char *s,FILE f); khng ghi \n, tr v k t cui ghi tp int fprintf(FILE *f, const char *dk,...); tr v s byte ghi tp + c: int *fgets(char *s,int n,FILE *f); int fscanf(FILE *f, const char *dk, ...); - Cc hm c ghi kiu nh phn (thch hp tp nh phn)

+ Ghi: int putw(int n, FILE *f); int fwrite(void *p, int size, int n, FILE *f); c tr cho struct + c: int getw(FILE *f); int fread(void *p,int size, int n, FILE *f); c tr cho struct 3.3. ng tp int fclose(FILE *f); ng tp sau khi y ht d liu t vng m ln a. Hm bng 0 nu ng. 3.4. Cc hm h tr khc Cc hm thng dng: . int feof(FILE *f): Kim tra cui tp, cha kt thc tp = 0. . int fflush(FILE *f) : lm sch vng m, ng= 0, sai = EOF . int ferror (FILE *f): li tao tc trn tp, ng =0 . void perror(const char *s): in chui v thng bo li h thng . int unlink(const char *s): xa tp s. ng = 0 . void remove(const char *s): xa tp s Cc hm lm vic vi nhiu tp . int fflushall(void) : lm sch vng m ca cc tp ang m. . int fcloseall(void): ng tt c cc tp ang m. Cc hm di chuyn con tr nh v void rewind(FILE *f); chuyn v u tp int fseek(FILE *f,long sb,int xp); t v tr xp, chuyn sb byte (+,-) xp c th l: SEEK_SET, SEEK_CUR, SEEK_END long ftell(FILE *f); v tr hin ti ca con tr nh v. V d tnh di ca tp fseek(f,0,SEEK_END); n=ftell(f); nu mi phn t ca tp c kch thc size th s phn t l n=ftell(f)/size;

* Ch : Khi bin con tr tp l stdprn th l my in.

4. Mt s bi tp
Bi 1 Vit chng trnh sao chp cc k t t tp source.dat sang tp dest.dat * Tc dng: - Sao chp trung thnh, dng tp nh phn. - Minh ha s dng cc hm c/ghi k t: fgetc, fputc
#include <stdio.h> #include <conio.h> main() { FILE *f1, *f2; char c; f1=fopen("source.dat","rb"); f2=fopen("dest.dat","wb"); if(f1==NULL) {printf("\n source file not exist"); getch(); exit();} while((c=fgetc(f1))!=EOF) fputc(c,f2); fclose(f1); fclose(f2); printf("\n Nhan phim bat ky de ket thuc chuong trinh."); getch(); }

Bi 2 To tp vn bn prims.txt cha n s nguyn t u tin (n <= 500). Lc ra cc s nguyn t i xng v ghi vo tp vn bn prim2.txt. Trn mi dng ca cc tp ni trn ghi 10 s, tr dng cui cng c th t hn. * Tc dng: Cch 1- Dng cc hm c/ghi d liu ln tp text theo khun dng: fscanf, fprintf Cch 2- Dng cc hm c/ ghi theo s nguyn (2B) getw, putw Cch 1
#include <stdio.h> #include <conio.h> #define fo1 "prims.txt" #define fo2 "prim2.txt"

long doixung(long x) {unsigned long y=0; while(x>0){y=y*10+x%10;x/=10;} return (y); } int prim(long x) {int d=0; long i=1; for(;i<=x/2;i++) if(x%i==0) d++; return(d==1?1:0); } main() { FILE *f1, *f2; long x; int c=0; char kt; const n = 200; f1=fopen(fo1,"wt"); for(x=2;c<n;x++) if(prim(x)) { c++; if(c%10==0) fprintf(f1,"%d\n",x); else fprintf(f1,"%d ",x); } fclose(f1); f1=fopen(fo1,"rt"); f2=fopen(fo2,"wt"); c=0; while(!feof(f1)) { fscanf(f1,"%ld",&x); if(!feof(f1)) if(x==doixung(x)) { fprintf(f2,"%ld ",x);c++; if(c%10==0) fprintf(f2,"\n"); } } fclose(f1); fclose(f2); }

Cch 2
#include <stdio.h> #include <conio.h> #define fo1 "prims.txt" #define fo2 "prim2.txt" long doixung(long x)

{unsigned long y=0; while(x>0){y=y*10+x%10;x/=10;} return (y); } int prim(long x) {int d=0; long i=1; for(;i<=x/2;i++) if(x%i==0) d++; return(d==1?1:0); } void main() { FILE *f1, *f2; long x; char kt; int c=0; const n = 200; f1=fopen(fo1,"wb"); for(x=2;c<n;x++) if(prim(x)) { c++; putw(x,f1);} fclose(f1); f1=fopen(fo1,"rb"); f2=fopen(fo2,"wb"); while(!feof(f1)) { x=getw(f1); if(!feof(f1)) if(x==doixung(x)) {putw(x,f2); printf("%d\t",x);} } fclose(f1); fclose(f2); }

Bi 3 M phng chng trnh son tho vn bn. Nhn v in ln mn hnh v tp vn bn (c tn nhp t bn phm) cc k t bt k c m > 31 (tr k t m 13). Chng trnh kt thc khi nhn Ctrl-C. * Tc dng - Cch 1: S dng cc hm getche() nhn v hin k t bt k, hm fputc - Cch 2: S dng cc hm fgets v fputs Cch 1
#include <stdio.h> #include <conio.h> void main() {

FILE *f; char c; char namef[11]; clrscr(); printf("File name: "); scanf("%s",namef); for(c=0;c<79;c++) printf("-"); printf("\n"); f=fopen(namef,"wt"); while((c=getche())!=3) {if(c>31||c==13) fputc(c,f); if(c==13) printf("\n"); } fclose(f); printf("\n File is copied."); getch(); }

Cch 2 Th hin on trnh sau y: char d[256]; while (1){ gets(d); if(d[0]==\0) break; fputc(10,f); fputs(d,f); } c ni dung ca tp vn bn v in ln mn hnh, ta dng on chng trnh char d[256]; while (1){ fgets(d,256,d); printf(%s,d); } Bi 4 Vit chng trnh to tp (nh phn) cha cc cu trc m t thng tin v cc sinh vin (gm h tn v nm sinh). Sau c danh sch sinh vin t tp ny in ra mn hnh. * Tc dng

- S dng cc hm fwrite, fread - n li cch truyn con tr cu trc cho hm.


#include <stdio.h> #include <conio.h> #define fname "sinhvien.dat" typedef struct{ char ht[30]; int ns; } sinhvien; const int size = sizeof(sinhvien); int nhapsv(sinhvien *sv) { sinhvien svtg; printf("\n ho ten: "); fflush(stdin); gets(svtg.ht); if(svtg.ht[0]=='\0') return (0); printf("\n nhap nam sinh: "); scanf("%d",&svtg.ns); *sv=svtg; return 1; } void xemsv(sinhvien sv) { printf("\n%s: %d ",sv.ht,sv.ns);} void main(){ FILE *f; sinhvien sv; f=fopen(fname,"wb"); while(1) {if(nhapsv(&sv)==0) break; fwrite(&sv,size,1,f); } fclose(f); f=fopen(fname,"rb"); while(fread(&sv,size,1,f)>0) xemsv(sv); fclose(f); getch(); }

Bi 2. CC HM NHP XUT CP 1

1. Cc tp tiu v bin chun


io/h fcntl.h sys/stat.h dos.h cha cc nguyn mu ca cc hm cp 1 cha cc nh ngha quyn truy nhp (access) cha cc nh ngha thuc tnh (amode) cha cc nh ngha thuc tnh (attribute) theo DOS

2. Tm tt cc hm
Cc hm to, m ng tp . creat v _creat: to tp mi . open v _open: m tp mi hoc c . close v _close: ng tp . chmod v _chmode : thay i thuc tnh tp ( _ l theo kiu DOS) . perror: thng bo li (stdio.h) . write, read : ghi/c dy cc byte . lseek: di chuyn con tr nh v tp. * UNIX v DOS - Kiu truy nhp mc nh ca cc hm trn l tp vn bn. Nu thm _ th mc nh l tp nh phn. - Thuc tnh trong cc hm create, chmod l cc hng c c trng ca UNIX, nh ngha trong sys/stat. Thuc tnh trong cc hm _create, _chmod l cc hng c c trng ca DOS nh ngha trong dos.h

3. C php ca cc hm
3.1. To tp int creat(const char *fname, int amode); - Tr v -1 khi li, ngc li, tr v s hiu tp. Trong sys/stat.h - amode l mt trong 2 hng: S_IREAD: ch c. Khng xa ,sa, b sung. S_IWRITE: ghi. c xa,sa,b sung. Kiu ghi c gn trong bin:

fmode ( mc nh l OTEXT, nh phn l O_BINARY) int _creat(const char *fname, int attrib); - Tr v -1 khi li, ngc li, tr v s hiu tp. Trong dos.h amode l mt trong 2 hng: - attrib l mt trong cc hng hoc t hp c ngha cc hng: FA_RONLY: ch c. FA_ARCH: ghi. FA_HIDDEN: tp n. 3.2. M tp int open(const char *fname, int access, [, unsigned amode]); - M tp v truy nhp theo quy nh ca access. Trong fcntl.h - access l mt trong cc hng hoc t hp cc hng: O_RONLY: c O_RDWR: c/ghi O_APPEND: Ghi b sung O_TRUNC: Xa tp nu tn ti, gi li thuc tnh O_TEXT: truy nhp kiu tp vn bn O_BINARY: truy nhp kiu tp nh phn O_CREATE: nu tp cha c th to mi. int _open(const char *fname, int oflags); - M tp thnh cng = 0, li = -1. - oflags xc nh quyn v kiu truy nhp ging nh access ca hm open v cng c cc gi tr hng nh trn. Tuy nhin mc nh l tp nh phn (O_BINARY) v hng O_CREATE khng c tc dng to tp mi. 3.3. ng tp int close(int fn); int _close(fn); - ng tp c s hiu fn. Hm thnh cng cho gi tr 0, li cho gi tr -1. 3.4. Thay i thuc tnh tp int chmod(const char *fname, int amode);

- Thnh cng=0, li = -1 - amode l mt trong cc hng nu. int _chmod(const char *fname, int func, [,int attrib]); - Thnh cng=0, li = -1 - Nu func=0, hm cho bit thuc tnh tp, khng cn i th 3. - Nu func=1, hm thay i thuc tnh tp theo quy nh trong attrib. Gi tr ca attrib nh nu. 3.5. Ghi/ c v di chuyn v tr trn tp unsigned write(int fn, void *ptr, unsigned n); unsigned read(int fn, void *ptr, unsigned n); - Ghi/c n byte gia vng nh ptr v tp c s hiu fn. - Thnh cng, hm tr s byte ghi/c c, li hm tr v -1 long lseek(int fn, long sb, int xp); di chuyn con tr nh v ca tp s hiu fn t v tr xp i sb byte. Du ca sb l chiu di chuyn.

4. Mt s bi tp
Bi 1 Thc hin vic sao chp tp bng cc hm cp 1 - S dng cc hm _open, _creat, read v write
#include <stdio.h> #include <conio.h> #include <io.h> #include <dos.h> #include <fcntl.h> void main(){ int n; char tep1[11], tep2[11]; char copy[1000]; int fn1, fn2; printf("\n nhap ten tep nguon: "); gets(tep1); printf("\n nhap ten tep dich: "); gets(tep2); fn1=_open(tep1,O_RDONLY); if(fn1==-1) { printf("\n tep nguon khong co."); return; } fn2=_creat(tep2,FA_ARCH); if(fn2==-1) { printf("\n loi tao tep dich."); return; } while((n=read(fn1,copy,1000))>0) write(fn2,copy,n);

close(fn1); close(fn2); printf("\n copied."); getch(); }

Bi 2 Thc hin vic thay i thuc tnh ca tp


#include <stdio.h> #include <conio.h> #include <io.h> #include <dos.h> #include <fcntl.h> void main(){ char tep[11]; int chon; int attrib; printf("\n nhap ten tep can thay doi thuoc tinh: "); gets(tep); printf("\n chon thuoc tinh: \ 0: ghi, 1: chi doc, Cong them 2 neu muon them hidden: "); chon=getche()-'0'; if(chon==0) attrib=FA_ARCH; else if(chon==1) attrib=FA_RDONLY; if(chon>=2) attrib=attrib | FA_HIDDEN; if(_chmod(tep,1,attrib)==-1) perror("\nloi thuc hien thay doi thuoc tinh"); else printf("\n attributed."); getch(); }