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

Switch / case Day3

                                  Lệnh điều kiện Switch/Case trong C
I.Khái niệm
 -Về cơ bản, lệnh điều kiện "switch/case" tương tự vs "if...else" để biểu diễn biểu thức điều kiện có khả năng xảy ra nhiều kết quả khác nhau.
-Nếu một trong số các câu lệnh trong biểu thức "switch" nào thỏa mãn, máy tính sẽ thực hiện câu lệnh đó.Trong trường hợp không có câu lệnh nào thỏa mãn, máy sẽ thực hiện lệnh cuối cùng
II.Cấu trúc
 -Cơ bản thì cấu trúc lệnh đk switch như sau:
 
  Switch (Biểu thức){
       Case hằng số 1:
               Câu lệnh;
               Break;
       Case hằng số 2:
               Câu lệnh;
               Break;
       Case hằng số 3:
               Câu lệnh;
               Break;
       Default:
               Câu lệnh;
}
 -Lệnh Break; dùng để thoát khỏi Case, trường hợp lệnh thỏa mãn nằm ở giữa thì lệnh này sẽ giúp kết thúc chương trình và đưa ra kết quả thỏa mãn cần tìm.
-Từ khóa Default: có chức năng tương tự Else, khi không có Case nào thỏa mãn, thì máy tính sẽ thực hiện lệnh trong Default
III.Bài tập
**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.

**Lưu đồ:



**Code:

#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 x; int y; printf("Nhap vao gia tri x = "); scanf("%d", &x); printf("Nhap vao gia tri y = "); scanf("%d", &y); if (x < 2000) { printf("\nGia tri thoa man x = %d", x); } else if (x > 3000) { printf("\nGia tri x thoa man = %d", x); } if (100<y<500) { printf("\nGia tri y thoa man = %d", y); } else printf("Error!!"); return 0; }


Lưu ý: Ở bài này chúng ta cần để ý điều kiện để thỏa mãn giá trị x,vì x không thể đồng thời thỏa mãn (x <2000 và x>3000) cho nên ta phải dùng else if cho một trong hai điều kiện


**Bài 2**: Write a program to show your computer’s capabilities. The user types in a letter of the alphabet and your program should display the corresponding language or package available. Some sample input ans output is given below :
                           Input                                  Output
                           A or a                                Ada
                           B or b                                 Basic
                           C or c                                 COBOL
                           D or d                                dBASE III
                           f or F                                  Fortran
                           p or P                                 Pascal
                           v or V                                Visual C++
Using the ‘switch’ statement to choose and display the appropriate message. Use the
default label to display a message if the input does not match any of the above         
letters.

**Lưu đồ:



**Code:

#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 letter; printf("Nhap vao ky tu : "); scanf("%s", &letter); switch(letter){ case 'A': case 'a': printf("\nAda"); break; case 'B': case 'b': printf("\nBasic"); break; case 'C': case 'c': printf("\nCOBOL"); break; case 'D': case 'd': printf("\ndBASE III"); break; case 'F': case 'f': printf("\nFortran"); break; case 'P': case 'p': printf("\nPascal"); break; case 'V': case 'v': printf("\nVisual C++"); break; default: printf("\nKhong tim thay ky tu thoa man!!"); } return 0; }



**Bài 3**: Accept values in three variables and print the highest value.
**Lưu đồ:


Lưu ý: Như trong định nghĩa lưu đồ đã học ở những bài trước, đây chỉ là sơ đồ tư duy cơ bản, có thể hơi khác về quá trình lập lý luận nhưng kết quả vẫn đúng với tư duy ban đầu.

**Code:

#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 vao a = "); scanf("%d", &a); printf("nhap vao b = "); scanf("%d", &b); printf("nhap vao c = "); scanf("%d", &c); if(a > b && a > c) { printf("\nGia tri lon nhat = %d", a); } else if(b > c && b > a) { printf("\nGia tri lon nhat = %d", b); } else if(c > a && c > b) { printf("\nGia tri lon nhat = %d", c); } else printf("Nothing"); return 0; }

Lưu ý: Ở bài này thì lệnh "Else" chỉ là cho đủ cú pháp, còn không có thể có trường hợp xảy ra lệnh đó được, vì trong 3 số có giá trị được gán cho thuộc tập xác định, chắn chắc có MỘT số lớn hơn cả 2 số còn lại.

Bài tập Day3 ( gets()/ puts() )

                                    Hàm gets() và puts()

I.Lý thuyết
-Hàm gets() là một trong những hàm cơ bản nhất, được dùng để đọc và nhập vào một chuỗi ký tự (string) bao gồm cả ký hiệu đặc biệt như \n hay khoảng trắng (phím space), và hàm này được kết thúc bằng phím Enter.
-Hàm puts() cũng là những hàm cơ bản, dùng để in và xuất ra một chuỗi ký tự, đồng thời hàm này thêm vào kí hiệu \n một cách tự động, và sẽ không in ra kí hiệu kết thúc chuỗi.

II.Bài tập
**Bài 1**: 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; int b; int c; printf("nhap vao gia tri a = "); scanf("%d", &a); printf("nhap vao gia tri b = "); scanf("%d", &b); printf("nhap vao gia tri c = "); scanf("%d", &c); printf("Tong cua ba so = %d", a + b + c); return 0; }

**Bài 2**: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 = 10;
  int b = 7;
  float c = 15.75;
  int d = 4;
  int e = 2;
  float f = 5.6;
  float z;
  printf("Gia tri cua z = %f", z = a*b+(c/d)-e*f );
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[]) { int a; int b; printf("Nhap vao chieu dai a = "); scanf("%d", &a); printf("Nhap vao chieu rong b = "); scanf("%d", &b); printf("Dien tich hinh chu nhat = %d", a*b); printf("\nChu vi hinh chu nhat = %d", (a+b)*2); return 0; }

**Bài 4**: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[]) { int r; int h; float pi = 3.14; printf("Nhap vao ban kinh duong tron day r = "); scanf("%d", &r); printf("Nhap vao chieu cao h = "); scanf("%d", &h); printf("The tich hinh tru = %f", r*r*pi*h); 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 BS = 12000; int DA = BS*12/100; int HRA = 150; int TA = 120; int Other = 450; int PF = BS*14/100; int IT = BS*15/100; printf("\nYour net salary = %d $ ", BS+DA+HRA+TA+Other-(PF+IT) ); return 0; }


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

Bài tập Day3 (More if)

                                                            Điều kiện "If ... Else"
I, Khái niệm
 -Mệnh lênh "If" và mệnh lệnh "else" có thể theo sau như 1 cặp và thực thi những mệnh lệnh có thể có các kết quả khác nhau tùy theo giá trị biến nhập vào.Mệnh lệnh "Else" sẽ chạy khi kết quả ở mệnh lệnh "If" không thỏa mãn.
*>Cú pháp:
-Trong môn C, mệnh lệnh if else thông thường có cú pháp dạng như:

 if(boolean_expression)
{
printf("/* statement(s) will execute if the boolean expression is true */");
}
else
{
      printf("/* statement(s) will execute if the boolean expression is false */");
  }
-if và else
-Nếu kết quả được thỏa mãn đúng ở mệnh lệnh nào, chương trình sẽ kết thúc tại mệnh lệnh đó.

II.Toán tử Else If
- "If" và "else" đi với nhau thành 1 cặp, nhưng trong trường hợp nhiều hơn 2 điều kiện mệnh lệnh, thay vì dùng nhiều cặp "If" "Else" với các ngoặc xoắn, ta dùng lệnh "Else if", thực chất lệnh này hoạt động như 2 lệnh cơ bản ở trên, chương trình sẽ kết thúc ở bất kỳ lệnh nào cho kết quả thỏa mãn.

III.If lồng If
-Khi gặp các trường hợp trong 1 lệnh trong số n lệnh phải bao gồm thêm một hoặc vài trường hợp nữa, ta sẽ dùng cấu trúc If lồng If.
-Thường cấu trúc if lồng nhau càng nhiều cấp độ phức tạp càng cao, chương trình chạy càng chậm và trong lúc lập trình dễ bị nhầm lẫn.Và, các lệnh if…else lồng nhau thì else sẽ luôn luôn kết hợp với if nào chưa có else gần nhất. Vì vậy khi gặp những lệnh if không có else, Bạn phải đặt chúng trong những khối lệnh được bọc bởi cặp ngoặc xoắn {} rõ ràng để tránh bị hiểu sai câu lệnh. 

IV.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.

**BÀI LÀM**


#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 vao a = ");
scanf("%d", &a);
printf("nhap vao 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.

**BÀI LÀM**

#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 vao a = ");
scanf("%d", &a);
printf("nhap vao b = ");
scanf("%d", &b);
r = b + a;
if(r == 1000)
{
printf("tong r cua a va b bang 1000");
}
else
{
    printf("tong r cua a va b khac 1000");
    }
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

**BÀI LÀM**
#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; printf("nhap vao a = "); scanf("%d", &a); printf("nhap vao b = "); scanf("%d", &b); if(a == b) { printf("hai gia tri nhap vao bang nhau"); } else { printf("hai gia tri nhap vao khong bang"); } 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 ).

**BÀI LÀM**

#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 grade; int salary; printf("Your basic salary is "); scanf("%d", &salary); 
fflush(stdin); printf("Your grade is "); grade = getchar();
if(grade == 'A') { printf("salary = %d",salary + 300); } else if(grade == 'B') { printf("salary = %d",salary + 250); } else { printf("salary = %d",salary + 100); } return 0; }

Lưu ý: Vì bài trên yêu cầu nhập trình độ grade ở đinh dạng biến char để tính lương, nhưng khi điền A ở mệnh lệnh If trong ngoặc sẽ báo lỗi chưa khai báo biến A, dĩ nhiên bài này A không phải 1 biến mà là chỉ là 1 thông số dẫn tới kết quả cuối.Vậy ta dùng hàm getchar để nhập 1 ký tự, và vì hàm này nhận cả ký hiệu \n cho nên phải dùng fflush(stdin) trước khi dùng


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


If marks >75 – grade A

If 60< marks < 75 – grade B
If 45<marks<60 – grade C
If 35<marks<45 - grade D
If marks < 35 – grade E

**BÀI LÀM**

#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 > 75) { printf("Your grade is A"); } else if(mark <= 75 && mark >= 60) { printf("Your grade is B"); } else if(mark <= 60 && mark >= 45) { printf("Your grade is C"); } else if(mark <= 45 && mark >= 30) { printf("Your grade is D"); } else if(mark <=30 && mark >= 0) { printf("Your grade is F"); } else printf("Error"); return 0; }


V.Kết Luận
-Qua bài này giúp ta hiểu về khái niệm lệnh điều kiện "If...Else" để giải quyết những câu lệnh có nhiều kết quả tùy vào thông số biến ta gán, cùng vài trường hợp sử dụng cách lệnh "Else If" cho mệnh lệnh nhiều hơn 2 trường hợp ra kết quả

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

Bài tập Day2 (printf và scanf)

                                                                      Printf & Scanf
I.Khái niệm
 1.Printf
   -Là hàm được sử dụng để xuất dữ liệu cũng như hiện thị dữ liệu đã được định dạng ở đầu ra.
VD: + printf(“control string”,argument list);
 
+ int a;
printf("nhap vao gia tri a");
2.Scantf
-Là hàm được sử dụng để nhập dữ liệu đã được định dạng tại đầu vào, thường đi liền với hàm printf.
VD: int a
printf("nhap vao gia tri a= ");
scanf("%d", a);
II.Bài tập
***Bài 1***:
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
 1. Sử dụng hàm printf() và làm những yêu cầu sau: a) In ra giá trị nguyên của biến sum
b) In ra chuỗi "Welcome", theo một dòng mới
c) In ra biến ký tự "letter"
d) In ra giá trị thực discount
e) In ra giá trị thức dump sử dụng 2 chữ số thập phân

#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=10;
printf("gia tri nguyen của bien = %d",sum); printf("\nWelcome\n"); printf("bien ki tu: letter"); float discount=3.6; printf("\nbien thuc thap phan=%0.2f",discount); float dump=6.03; printf("\nbien thức có 2 chữ số thập phân=%0.2f",dump);

***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
Sử dụng hàm scanf() và làm:
a) Đọc giá trị thập phân từ bàn phím, và in ra biến nguyên "sum"
b) Đọc giá trị thực và in ra biến "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[]) {
int sum;
    printf("SUM = ");
    scanf("%d",&sum);
    printf("\ngia tri nguyen la: %d \n",sum);
    float discount_rate;
    printf("\ndiscount_rate: ");
    scanf("%f",&discount_rate);
    printf("\ngia tri thuc la: %f",discount_rate);
    printf("\n");
    system("pause");
  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
#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 name[10];
int basic, daper; float bonper, loandet, salary; printf("name: "); scanf("%s",name); printf("\nbasic = "); scanf("%d",&basic); printf("\ndaper = "); scanf("%d",&daper); printf("\nbonper = "); scanf("%f",&bonper); printf("\nloandet = "); scanf("%f",&loandet); salary = basic + basic * daper/100 + bonper * basic/100 - loandet;  
printf("\nName \tBasic \tSalary"); return 0; }
***Bài 4***:Viết chương trình hỏi họ và tên bạn, cuối cùng in ra định dạng tên và họ của bạn

#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 firstname[10]; char lastname[20]; printf("\nfirstname : "); scanf("%s", firstname); printf("\nlastname : "); scanf("%s", lastname); printf("\nyour name is : %s%s", firstname, lastname);