Sau đây là các tuyên bố đưa ra quyết định -
- đơn giản - câu lệnh if
- câu lệnh if - else
- lồng nhau - câu lệnh if else
- else - if bậc thang
- câu lệnh switch
Đơn giản - câu lệnh if
Từ khóa ‘if’ được sử dụng để thực thi một tập hợp các câu lệnh khi điều kiện logic là đúng.
Cú pháp
if (condition){
Statement (s)
}
Ví dụ
Ví dụ sau kiểm tra xem một số có lớn hơn 50 hay không.
#include<stdio.h>
main (){
int a;
printf (“enter any number:\n”);
scanf (“%d”, &a);
if (a>50)
printf (“%d is greater than 50”, a);
} Đầu ra
1) enter any number: 60 60 is greater than 50 . 2) enter any number 20 no output
Câu lệnh if else
Câu lệnh if –else có điều kiện Đúng hoặc Sai.
Cú pháp
if (condition){
True block statement(s)
}
else{
False block statement(s)
} Lưu đồ
Ví dụ
Sau đây là chương trình để kiểm tra số chẵn hay lẻ -
#include<stdio.h>
main (){
int n;
printf (“enter any number:\n”);
scanf (“%d”, &n);
if (n%2 ==0)
printf (“%d is even number”, n);
else
printf( “%d is odd number”, n);
} Đầu ra
1) enter any number: 10 10 is even number
Câu lệnh if - else lồng nhau
Ở đây "if" được đặt bên trong if (hoặc) else -
Cú pháp
if (condition1){
if (condition2)
stmt1;
else
stmt2;
}
else{
if (condition3)
stmt3;
else
stmt4;
} Lưu đồ
Ví dụ
Ví dụ sau là in ra số lớn nhất trong 3 số từ các số đã cho -
#include<stdio.h>
main (){
int a,b,c;
printf (“enter 3 numbers”);
scanf (“%d%d%d”, &a, &b, &c);
if (a>b){
if (a>c)
printf (“%d is largest”, a);
else
printf (“%d is largest”, c);
} else {
if (b>c)
printf (“%d is largest”, b);
else
printf (“%d is largest”, c);
}
} Đầu ra
enter 3 numbers = 10 20 30 30 is largest
Khác - nếu bậc thang
Đây là một điều kiện quyết định nhiều chiều.
Cú pháp
if (condition1) stmt1; else if (condition2) stmt2; - - - - - - - - - - else if (condition n) stmt n; else stmt x;
Lưu đồ
Ví dụ
Ví dụ sau tìm nghiệm của phương trình bậc hai -
#include <math.h>
main (){
int a,b,c,d;
float r1, r2
printf ("enter the values a b c");
scanf (“%d%d%d”, &a, &b, &c);
d= b*b – 4*a*c ;
if (d>0){
r1 = (-b+sqrt(d)) / (2*a);
r2 = (-b-sqrt(d)) / (2*a);
printf (“root1 ,root2 =%f%f”, r1, r2);
}
else if (d== 0){
r1 = -b / (2*a);
r2 = -b/ (2*a);
printf (“root1, root2 = %f%f”, r1, r2);
}
else
printf ("roots are imaginary”);
} Đầu ra
1) enter the values of a b c : 1 4 3 Root 1 = -1 Root 2 = -3
Câu lệnh chuyển đổi
Sẽ rất hữu ích khi chọn một trong số nhiều quyết định.
Cú pháp
switch (expression){
case value1 : stmt1;
break;
case value2 : stmt2;
break;
- - - - - -
default : stmt – x;
} Cú pháp
Ví dụ
#include<stdio.h>
main (){
int n;
printf (“enter a number”);
scanf (“%d”, &n);
switch (n){
case 0 : printf (“zero”)
break;
case 1 : printf (‘one”);
break;
default : printf (‘wrong choice”);
}
} Đầu ra
enter a number 1 One