Mot so kien thc c s ve lap trnh bang ngon ng C

Phan trc | Muc luc | Phan sau

III. Cac thanh phan c s cua chng trnh C

Noi dung:

Vi phan nay ta lam quen vi cac thanh phan c s cau tao nen ngon ng C:

 

Cac thanh phan c s

Hang va bien

Hang la ai lng khong thay oi gia tr trong qua trnh thi hanh chng trnh.
Bien la ai lng ma gia tr cua no co the thay oi trong qua trnh thi hanh chng trnh.

Bieu thc

Bieu thc la to hp cac hang, bien va cac toan t xac nh cac phep toan.

(2 + 3*i) / 10

Toan t so hoc

Ky hieu

Y ngha

+

Cong

-

Tr

*

Nhan

/

Chia

%

Phan d (modulo)

Cau lenh

Cau lenh la mot to hp co ngha ( 2 ve) cac bieu thc va cham dt bi dau cham phay (;).

i = (2 + 3) * 10;
i = 2 + 3 * 10;
j = 6 % 4;
k = i + j;
 
return 0;
exit(0);
printf ("Ket thuc chuong trinh");

Cum cau lenh

Cum cau lenh la nhom cau lenh bat au bang ngoac { va ket thuc bang ngoac }. Cum cau lenh c thi hanh nh mot cau lenh bi bo bien dch C.

for(. . .) {
 s3 = s1 + s2;
 mul = s3 * c;
 remainder = sum % c;
}

Cau truc mot ham C

Mot ham c cau tao bi 6 phan:
- Kieu ham
- Ten ham
- oi so
- Ngoac m {
- Than ham
- Ngoac ong }

Kieu ham la kieu d lieu ma ham se tra. Mac nh ham tra kieu int. Kieu void se khong tra gia g nao ca.
Ten ham phai co ngha va ung cu phap.

Ten khong ung

Cu phap

2 (digit)

Ten ham khong c khi au bang so

* (Asterisk)

Ten ham khong c khi au bang dau

+ (Addition)

Ten ham khong c khi au bang t khoa

. (dot)

Ten ham khong c khi au bang .

total-number

Ten ham khong c cha ky hieu toan t

account'97

Ten ham khong c cha dau ‘

Ten hp le: print2copy, total_number, _quick_add, Method3

oi so ham C

oi so la nhng bien nam trong ngoac n sau ten ham. oi so ham C ch co tnh tham tr, ngha la no ch truyen gia tr vao trong ham ch khong thay oi gia tr ngoai ham.

V du: Ham cong 2 so nguyen

1: /* This function adds two integers and returns the result */
2: int integer_add( int x, int y )
3: {
4: int result;
5: result = x + y;
6: return result;
7: }
 

Li khuyen

Khong nen tao ham qua phc tap va dai, manen chia nho (tao nhieu ham con) ra e de dang theo doi trong qua trnh ieu chnh hoac s loi chng trnh.

Cach goi ham

V du: Chng trnh tnh phep cong va xuat gia tr len man anh

1: /* Calculate an addition and print out the result */
2: #include <stdio.h>
3: /* This function adds two integers and returns the result */
4: int integer_add( int x, int y )
5: {
6: int result;
7: result = x + y;
8: return result;
9: }
10:
11: int main()
12: {
13: int sum;
14:
15: sum = integer_add( 5, 12);
16: printf("The addition of 5 and 12 is %d.\n", sum);
17: return 0;
18: }

Bai tap

  1. Viet mot ham C nhan 2 so nguyen vi nhau va tra lai gia tr nhan.
  2. Viet chng trnh goi ham nhan BT1 e nhan 3 vi 5 va xuat ket qua len man anh.

 

Phan trc | Muc luc | Phan sau

 

Previous | Table of Contents | Next