Thứ Bảy, 31 tháng 1, 2015

switch...case

Filled under:

- Cấu trúc switch...case dùng để kiểm tra một vài giá trị hằng cho một biểu thức.
- Cấu trúc của nó như sau:

switch(expression){
    case constant1:
         statements1;
         break;
    case constant2:
         statements2;
         break;
    case constant3:
         statements3;
         break;
    ...
    default:
         statements;


- Nó sẽ hoạt động như sau: switch tính biểu thức và kiểm tra xem nó có bằng constant1 hay không, nếu đúng thì nó thực hiện statements1 cho đến khi tìm thấy từ khóa break; Còn nếu không, switch sẽ kiểm tra xem biểu thức có bằng constant2 hay không. Nếu đúng nó sẽ thực hiện statements2 cho đến khi tìm thấy từ khoá break;. Cuối cùng, nếu giá trị biểu thức không bằng bất kỳ hằng nào được chỉ định ở trên (bạn có thể chỉ định bao nhiêu câu lệnh case tuỳ thích), chương trình sẽ thực hiện các lệnh trong phần default: 
- Lưu ý: Lệnh break; ở mỗi khối lệnh rất quan trọng, nó dùng để ngắt cho máy tính không chạy các dòng tiếp theo khi đã tìm được điều kiện đúng.

Bài 1: Declare two variables x and y. Assign values to these variables. Number x should be printed only if it

is less than 2000 or greater than 3000, and number y should be printed only if it is between 100 and 500.




Bài 2: Accept values in three variables and print the highest value.



Posted By Unknown01:26

gets() và puts()

Filled under:

I. Hàm gets()
- Cú pháp:
gets(string);
- Hàm gets cũng giống như hàm scanf được dùng để nhập dữ liệu từ thiết bị nhập chuẩn.
- Sự khác nhau giữa hàm gets và scanf:
+ Hàm scanf khi nhập vào một chuỗi thì nó sẽ kết thúc khi gặp một khoảng trắng, vì vậy hàm scanf rất khó lưu chuỗi mà có chứa khoảng trắng.
+ Hàm gets sẽ chỉ kết thúc khi ta nhấn enter, có nghĩa là hàm gets dễ dàng lưu được một chuỗi mà có chứa khoảng trắng.
II. Hàm puts()
- Cú pháp:
puts(string);
- Hàm puts cũng giống như printf được dùng để xuất dữ liệu ra ngoài màn hình nhưng hàm puts đơn giản hơn

III. Bài tập:

Bài 1: Write a program to accept and add three numbers.

****************************************************

#include <stdio.h> #include <stdlib.h> /* run this program using the console pauser or add your own getch, system("pause") or input loop */ int main(int argc, char *argv[]) { int a,b,c; puts("Nhap so thu nhat:"); scanf("%d", &a); puts("Nhap so thu hai:"); scanf("%d", &b); puts("Nhap so thu ba:"); scanf("%d", &c); return 0; }

****************************************************

Bài 2: For the following values, write a program to evaluate the expression

z = a*b+(c/d)-e*f ;

  a=10
  b=7
  c=15.75
  d=4
  e=2
  f=5.6      

****************************************************

#include <stdio.h> #include <stdlib.h> /* run this program using the console pauser or add your own getch, system("pause") or input loop */ int main(int argc, char *argv[]) { int a,b,d,e; float c,f,z; a=10; b=7; c=15.75; d=4; e=2; f=5.6; z=a*b+(c/d)-e*f; printf("z = %f", z); return 0; }

****************************************************

Bài 3: Write a program to evaluate the area and perimeter of the rectangle.

****************************************************

#include <stdio.h> #include <stdlib.h> /* run this program using the console pauser or add your own getch, system("pause") or input loop */ int main(int argc, char *argv[]) { float x,y; printf("Nhap chieu dai HCN:"); scanf("%f", &x); printf("Nhap chieu rong HCN:"); scanf("%f", &y); printf("\nChu vi hinh chu nhat la: %f", (x+y)*2); printf("\nDien tich hinh chu nhat la: %f", x*y); return 0; }

****************************************************

Bài 4: Write a program to evaluate the volume of a cylinder.

****************************************************

#include <stdio.h> #include <stdlib.h> /* run this program using the console pauser or add your own getch, system("pause") or input loop */ int main(int argc, char *argv[]) { float x,y; printf("Nhap ban kinh day:"); scanf("%f", &x); printf("Nhap chieu cao hinh tru:"); scanf("%f", &y); printf("The tich cua hinh tru la: %f", 3.14*x*x*y); return 0; }

****************************************************

Bài 5: Write a program to evaluate the net salary of an employee given the following constraints
Basic salary : $ 12000
DA : 12% of Basic salary
HRA : $150
TA : $120
Others : $450
Tax cuts – a) PF :14% of Basic salary and b) IT: 15% of Basic salary
Net Salary = Basic Salary + DA + HRA + TA + Others – (PF + IT)

****************************************************

#include <stdio.h> #include <stdlib.h> /* run this program using the console pauser or add your own getch, system("pause") or input loop */ int main(int argc, char *argv[]) { int basic_salary, DA, HRA, TA, others, PF,IT, net_salary; basic_salary = 12000; DA = basic_salary*12/100; HRA = 150; TA = 120; others = 450; PF = basic_salary*14/100; IT = basic_salary*15/100; net_salary = basic_salary + DA + HRA + others - (PF+IT); printf("Net salary: %d", net_salary); return 0; }

****************************************************


Posted By Unknown00:37

Thứ Sáu, 30 tháng 1, 2015

Lệnh điều kiện if, if...else

Filled under:

I. if
- Cấu trúc của câu lệnh if là:
if(điều kiện A){
          câu lệnh B;
}
- Câu điều kiện if có thể hiểu là nếu mà điều kiện A đúng thì sẽ thực hiện câu lệnh B.
- Nếu chỉ có một câu lệnh trong lệnh if thì ta có thể viết:
if(x>2)
printf("x lon hon 2");
- Nhưng nếu có 2 câu lệnh trở lên ta phải đặt 2 câu lệnh ấy trong dấu {}
if(x>2){
       printf("Gia tri cua x la %d", x);
       printf("Va x lon hon 2");
}
- Bởi vì nếu không đặt vào trong dấu {} thì câu lệnh if sẽ chỉ nhận dòng lệnh đầu tiên và dòng lệnh thứ 2 sẽ được hiều là một lệnh mới ngang hàng với if.
- Tuy nhiên chúng ta nên đặt câu lệnh trong dấu {} để tiện cho việc sửa chữa và bổ sung thêm câu lệnh.
II. if...else
- Cấu trúc của câu lệnh if...else là:
if(điều kiện A){
          câu lệnh B;
}
else{
          câu lệnh C;
}
- Câu điều kiện if...else có thể hiểu là nếu điều kiện A đúng thì thực hiện câu lệnh B, nếu không thì thực hiện câu lệnh C.

Lưu ý: - Câu lệnh if có thể đứng một mình còn else thì không, else chắc chắn phải đi với if.

- Đến đây có một vấn đề đặt ra đó là nếu một bài toán mà có nhiều điều kiện thì chúng ta sẽ phải viết nhiều dòng if và máy tính sẽ phải chạy hết những dòng lệnh if đó. Để giảm thời gian xử lý của máy tính người ta sẽ dùng lệnh if...else if...else....
if(điều kiện){
}
else if(điều kiện){
}
else if(điều kiện){
}
......
else{
}
- Máy tính sẽ xử lý các dòng lệnh và khi tìm được điều kiện đúng thì nó sẽ in ra luôn kết quả và bỏ qua những dòng lệnh còn lại, như vậy thời gian xử lý sẽ nhanh hơn.

III. Bài tập

Bài 1: Write a program that accepts two numbers a and b and checks whether or not a is divisible by b.

***********************************************************


#include <stdio.h>
#include <stdlib.h>

/* run this program using the console pauser or add your own getch, system("pause") or input loop */

int main(int argc, char *argv[]) {
int a;
int b;
int r;
printf("Nhap a:");
scanf("%d", &a); fflush(stdin);
printf("Nhap b:");
scanf("%d", &b);
r = b % a;
if(r==0){
printf("b chia het cho a");
}
else{
printf("b khong chia het cho a");
}
return 0;

}

***********************************************************

Bài 2: Write a program to accept 2 numbers and tell whether the product of the two numbers is equal to or greater than 1000.

***********************************************************

#include <stdio.h>
#include <stdlib.h>

/* run this program using the console pauser or add your own getch, system("pause") or input loop */

int main(int argc, char *argv[]) {
int a, b, c;
printf("Nhap a:");
scanf("%d", &a);
printf("Nhap b:");
scanf("%d", &b);
c = a + b;
if(c > 1000){
printf("Tong cua hai so la %d lon hon 1000", c);
}
else{
if(c==1000){
printf("Tong cua hai so la 1000");
}
else{
printf("Tong cua hai so la %d nho hon 1000", c);
}
}
return 0;
}

***********************************************************

Bài 3: Write a program to accept 2 numbers. Calculate the difference between the two values. If the difference is equal to any of the values entered, then display the following message :


Difference is equal to value <number of value entered>


If the difference is not equal to any of the values entered, display the following message:


Difference is not equal to any of the values entered

***********************************************************
#include <stdio.h>
#include <stdlib.h>

/* run this program using the console pauser or add your own getch, system("pause") or input loop */


int main(int argc, char *argv[]) {

int a, b;

printf("Nhap a:");
scanf("%d", &a);

printf("Nhap b:");
scanf("%d", &b);

if(a==b){
printf("a = b");
}
else{
printf("a khac b");
}
return 0;
}

***********************************************************

Bài 4: Montek company gives allowances to its employees depending on their grade as follows :
  Grade                                 Allowance
  A                                        300
  B                                        250
 Others                                100       
Calculate the salary at the end of the month.   (Accept Salary and Grade from the user ).

***********************************************************

#include <stdio.h> #include <stdlib.h> /* run this program using the console pauser or add your own getch, system("pause") or input loop */ int main(int argc, char** argv) { char cap; int luong; printf("Luong co ban cua ban la: "); scanf("%d", &luong); fflush(stdin); printf("Cap cua ban la: "); cap=getchar(); if(cap == 'A') { printf("Luong cua ban la : %d",luong + 300); } else if(cap == 'B') { printf("Luong cua ban la : %d",luong + 250); } else { printf("Luong cua ban la : %d",luong + 100); } return 0; }


***********************************************************

- Lưu ý: Ở đây A và B chỉ là những kí tự và để chỉ cấp độ của người dùng nên ta sẽ dùng lệnh getchar() thay cho scanf và trong lệnh if A và B phải được đặt trong dấu ''.

Bài 5: Write a program to evaluate the Grade of a student for the following constraints

***********************************************************

#include <stdio.h> #include <stdlib.h> /* run this program using the console pauser or add your own getch, system("pause") or input loop */ int main(int argc, char** argv) { int mark; printf("Your mark is "); scanf("%d", &mark); if(mark > 7.5) { printf("Your grade is A"); } else if(mark <= 7.5 && mark >= 6.0) { printf("Your grade is B"); } else if(mark <= 6.0 && mark >= 4.5) { printf("Your grade is C"); } else if(mark <= 4.5 && mark >= 3.0) { printf("Your grade is D"); } else { printf("Your grade is F"); } return 0; }

***********************************************************

Posted By Unknown23:21

Thứ Năm, 29 tháng 1, 2015

Printf & Scanf

Filled under:

I. Hàm printf

- Hàm printf là hàm dùng để xuất dữ liệu được định dạng
- Cú pháp:
printf("control string", argument list);
- Ví dụ:
+ printf("Xin chao");
+ int x;
   printf("%d", x);

II. Hàm scanf

- Hàm scanf là hàm dùng để định dạng khi nhập dữ liệu.
- Cú pháp:
scanf("control string", argument list);
- Ví dụ:
+ int x;
   printf("Nhap x:");
   scanf("%d", x);

III. Bài tập:

Bài 1: Use the printf( )  statement and do the following
a)    Print out the value of the integer variable sum
b)  Print out the text string "Welcome", followed by a new line.
c)  Print out the character variable letter
d)  Print out the float variable discount
e) Print out the float variable dump using two decimal places

****************************************************************************

#include <stdio.h> #include <stdlib.h> /* run this program using the console pauser or add your own getch, system("pause") or input loop */ int main(int argc, char *argv[]) { int sum=17; printf("the value of the integer variable = %d",sum); printf("\nWelcom\n"); printf("the character variable: letter"); float discount=1,51; printf("\nthe float variable discount=%f",discount); float dump=1,41; printf("\nthe float variable dump using two decimal places=%0.2f",dump); return 0; }

****************************************************************************

Bài 2: Use the scanf( )  statement and do the following:
a) To read a decimal value from the keyboard, into the integer variable sum
b) To read a float variable into the variable discount_rate

****************************************************************************

#include <stdio.h> #include <stdlib.h> /* run this program using the console pauser or add your own getch, system("pause") or input loop */ int main(int argc, char *argv[]) { // phan a float sum; printf("\nNhap mot so thap phan:"); scanf("%f", &sum);
// phan b float discount_rate; printf("\nNhap mot so:"); scanf("%f", &discount_rate); return 0; }

****************************************************************************

Bài 3: Write a program which takes name, basic , daper ( ie, percentage of D.A), bonper (ie, percentage bonus) and loandet ( loan amount to be debited) for an employee. Calculate the salary using the following relation:
salary = basic + basic * daper /100 +bonper                 
        *  basic/100 - loandet
Data is :
 
name
basic
daper
bonper
loandet
MARK
2500
55
33.33
250.00
Calculate salary and then print the result under the following headings.
(Salary to be printed to the nearest dollar.)
        Name                                    Basic                        Salary

****************************************************************************

#include <stdio.h> #include <stdlib.h> /* run this program using the console pauser or add your own getch, system("pause") or input loop */ int main(int argc, char *argv[]) { int basic=2500, daper=55; float bonper=33.33, loandet=250.00; float salary = basic+basic*daper/100+bonper*basic/100-loandet; printf("name:Mark\n"); printf("basic=%d\n",basic); printf("salary = %0.2f USD",salary); return 0; }

****************************************************************************

Bài 4: Write a program that asks for your first name and last name, and then prints the names in the format last name, first name.

****************************************************************************

#include <stdio.h>
#include <stdlib.h>

/* run this program using the console pauser or add your own getch, system("pause") or input loop */

int main(int argc, char *argv[]) {

char a[30];
char b[30];

printf("Your first name:");
scanf("%s", a);

printf("Your last name:");
scanf("%s", b);

printf("\nYour name is:%s %s", a,b);

return 0;
}

****************************************************************************

Lưu ý: Ví dụ nhập:
Your fist name: Le
Your last name: Tuan Anh
thì sẽ xuất hiện lỗi, tên hiển thị ra chỉ là Your name is Le Tuan
Bởi vì lệnh scanf sẽ kết thúc khi nó gặp khoảng trắng, nên nó chỉ đọc được Tuan mà không đọc được Tuan Anh.
Để khắc phục chúng ta sẽ sử dụng hàm gets thay cho scanf:

#include <stdio.h>
#include <stdlib.h>

/* run this program using the console pauser or add your own getch, system("pause") or input loop */

int main(int argc, char *argv[]) {

 char a[20];
 char b[20];

 printf("Your first name:");
 scanf("%s", a); fflush(stdin);

 printf("Your last name:");
 gets(b);

 printf("\nYour name is:%s %s", a,b);

 return 0;
}

Posted By Unknown02:27