Professional Documents
Culture Documents
BaigiangTH2 C5
BaigiangTH2 C5
}
… statement(s)
Next statement
3. int main() {
4. int b;
6. printf("Enter a value:");
7. scanf("%d", &b);
8. if (b < 0)
9. printf("The value \
is negative\n");
10. return 0;
11.}
Lập trình C - CNTT2. 2002 - 2005 12
if … else …
if (<dieu kien>)
{
/* cac lenh thuc hien neu dieu kien dung */
}
else
{ True
expression
False
/* cac lenh thuc hien
neu dieu kien sai */
statement1 statement2
}
…
Next statement
3. int main() {
4. int b;
6. printf("Enter a value:");
7. scanf("%d", &b);
8. if (b == 5)
9. printf(“b is "); printf( “5 \n”);
10. return 0;
11.}
3. printf("Enter a value:");
4. scanf("%d", &b);
5. if (b < 0)
6. printf("The value is negative\n");
7. else if (b == 0)
8. printf("The value is zero\n");
9. else
10. printf("The value is positive\n");
11. return 0;
12.}
Tuy nhiên, cần chú ý đến thứ tự các cặp lệnh if … else …
khi lồng các lệnh if. Nếu không sẽ phát sinh lỗi.
1. if ( X >= 0 )
2. if ( Y < 0 )
3. Y = Y + sqrt(X);
4. else
5. Y = Y + sqrt(-X);