Programming C: Posts 5 – if else, switch case in C
In life there are many things we have to choose, such as choosing between love and love people we, choose to listen to the heart or mind,… If today is a school holiday, would stay or go play, if people love it or go buy ice cream ZIP sit together to eat outside the school gates, etc. and cloudy cloudy. And programming is going from life, service life, it must have such things. This lesson we will learn about the command to serve such options, these commands called branch instruction.
Content
Before learning about the structure of the branch instruction, we should learn a little about the menu commands and command block.
1. The command and the block
Order a task, expression, jaw, control structure ... any single.
Example:
x = x + 2; // đây là một lệnh đơn printf("Day la mot lenh\n"); // đây cũng là một lệnh đơn.
block command: is a series of statements surrounded by braces { }.
Example:
{ //dau khoi a = 78; b = 26; printf("Tong %d + %d = %d", a, b, a+b); } //cuoi khoi
When you want to perform a series of consecutive commands that we use the command block, ie put them into the braces {} and write indented 1 tab for easy look.
Noted: When an order is placed in brackets {} it is also regarded as the command block.
2. If and if else
2.1 The if statement
The if statement translated means if this one do that. For example if you have a lover then you'll be going out with you rather watch your posts…
The syntax of an if statement
Attention:
Do not place a semicolon after the if statement. Example: if (a > 0);
When placing a semicolon in the if statement is regarded as ended if statement in the statement block that should not be done right or wrong whether conditions.
Example: Initially you 100 (billion), Please enter an amount. If the amount is positive, the plus in your wallet converse is not doing anything. Print out the amount you have after typing.
#include <stdio.h> int main() { int x = 100; // So tien ban dau ban co int y; // so tien nhap moi printf("Nhap so tien = "); scanf("%d", &y); if( y > 0 ) // neu so tien nhap vao lon hon 0 thi cong vao vi { x = x + y; } printf("So tien sau = %d \n", x); return 0; }
Very simple. You run the program and see how it works nhé.
2.2 The if statement – else
If-else statement is a sufficient form of an if statement. if if, else is contrary.
If statement syntax – else
Example: Similar examples. Initially you 100 (billion), wife you 50 (billion), Please enter an amount. If the amount is positive, the plus in your wallet half, Your wife's half, vice versa, only added to your wallet (nature is minus because the amount can be negative or equal 0). Print out the amount you and your wife have after typing.
#include <stdio.h> int main() { float x = 100, y = 50; // So tien ban va vo ban co float z; // so tien nhap moi printf("Nhap so tien = "); scanf("%f", &z); if( z > 0 ) // neu so tien nhap vao lon hon 0 thi cong vao vi { x = x + z / 2; y = y + z / 2; } else { x = x + z; } printf("So tien cua ban = %.2f \n", x); printf("So tien cua vo ban = %.2f \n", y); return 0; }
Pretty simple. You try to run and view results nhé. (In this article I used a float because the division can be the amount of retail).
2.3 Else nested if statements and if-else-if
In many cases, we need to treat many conditions, not only 1 condition. Therefore we can nest multiple else if statements together.
Example: The company is implementing a balanced so balanced pairs serve balanced lovers, and notice the heavier boyfriend or girlfriend or two you weigh heavier equal.
So we need to handle 3 case, not simply if and back again. We have the following code:
#include <stdio.h> int main() { float a; // can nang cua ban trai float b; // can nang cua ban gai printf("Nhap vao can nang ban trai va ban gai: \n"); scanf("%f%f", &a, &b); if( a > b ) { printf("Ban trai nang hon!\n"); } else { if( a < b) { printf("Ban gai nang hon\n"); } else { printf("Hai ban nang bang nhau\n"); } } return 0; }
Ok. So we use them interlocking. But this way will make the code a bit tangled and expensive ink. You can use if-else-if statement is as follows:
#include <stdio.h> int main() { float a; // can nang cua ban trai float b; // can nang cua ban gai printf("Nhap vao can nang ban trai va ban gai: \n"); scanf("%f%f", &a, &b); if( a > b ) { printf("Ban trai nang hon!\n"); } else if( a < b) { printf("Ban gai nang hon\n"); } else { printf("Hai ban nang bang nhau\n"); } return 0; }
How to code and also very clear sense, understandable :).
2.4 The conditional operator – If else shortened
We have a shorthand operator else if statement is as follows:
điều kiện ? biểu thứ 1: biểu thức 2;
If true, the expression conditions 1 is performed and the value of the expression 1 is the value of the entire command. If the condition is false, then the expression 2 is performed and the value of the expression 2 becomes the value of the entire command.
Example:
#include <stdio.h> int main() { int x = 3; int y = 4; int z; z = x > y ? x : y; printf("z = %d\n", z); x = x > y ? x : 100; printf("x = %d\n", x); return 0; }
Results after running the program:
z = 4
x = 100
Thus we see the expression 2 and expression 3 maybe 1 variable values, constant, hoặc một hàm nào đó có trả về giá trị.
2. A switch case
The switch statement is similar if structure, but it is softer and more flexible than using if. However, it also has drawbacks as a result of the expression must be integer constant value (specific value). Another problem is the command switch can also use if, whereas it also depends on the algorithms of problem.
Switch case structure
Example: Enter 1 number from 1-> 5 and print the corresponding reading:
#include <stdio.h> int main() { int a; printf("Nhap a = "); scanf("%d",&a); switch(a) { case 1: printf("Mot\n"); break; case 2: printf("Hai\n"); break; case 3: printf("Ba\n"); break; case 4: printf("Bon\n"); break; case 5: printf("Nam\n"); break; } return 0; }
You run, and try to give some see it break statement the star light.
Moreover, we structured the switch-case-default anymore. The principle works like a switch-case, but if the case is not satisfied, it will execute the default case (Translation is the default case).
#include <stdio.h> int main() { int a; printf("Nhap a = "); scanf("%d",&a); switch(a) { case 1: printf("Mot\n"); break; case 2: printf("Hai\n"); break; case 3: printf("Ba\n"); break; case 4: printf("Bon\n"); break; case 5: printf("Nam\n"); break; default: printf("Ban da nhap mot so khac\n"); break; } return 0; }
3. When to use if-else, When using switch-case
Like I said above, switch case with the flexibility and mobility than if else, also transient and difficult spelling mistake than if else but a pilot case all user switch certainly be used by the user if else if else also unlikely to be used by the switch case.
So you should use the switch case:
- Large number of conditions such as shape selection menu,… -> Switch case would write desert creek, easy to control.
- The case conditions must be an integer value or character.
The other cases, if you use – else.
Exercise:
- Write a program to 4 integer. Find and print the largest number.
Guide: I have 4 integer a, b, c, d. Violet 2 largest integer x, y 2 pair (the, b) and (c, d). Then compare x and y to find the largest integer.Please enter a number that 1 the month of the year, print see how many days of the month. (Regarded as no leap year).
Let programmers program the quadratic equation 2: with a, b, c typing.
Write a program to 3 a positive integer value, b, c. Check if a, b, c Is 3 edge of the triangle is not? If 3 edge of the triangle, the triangle area calculation formula:
where p is half the perimeter of the triangle.
Write a program that includes charges for electricity following conditions:
- Subscription galvanometer: 1000e / month
- The electricity usage per household: 50 KW for 230D / KW
- If the excess amount <= 50KW, the pricing 480D / KW
- If 50KW < the excess amount < 100KW is charged VND700 / K
If the excess amount> = 100KW then charged to 900 dong / KW
New and old index is entered from the keyboard. In the old index screen, new index, pay norms, payments beyond the norm, the total amount payable.
Backing up the same map so a and b? admin considered to go.
For eg admin case b for clarity. Thanks!
Thank you. Its revised and more examples I got you.
Bạn viết rất súc tích và dễ hiểu, cảm ơn nhiều! nếu có thể bạn cho mình thêm nhiều bài tập cơ bản nữa được không?
Bài tập cơ bản thì mình chỉ nghĩ ra vậy thôi. Khi lf các bài lớn sẽ dùng rất nhiều 😉
có phần giải bài tập không anh
Bài tập các bạn tự giải hoặc thảo luận với nhau nhé
This is the code the quadratic equation 2 e sir ! E novice C should also expect a place not only help correct !
#include
#include
#include
int main(){
int a, b, c;
printf(” Quadratic phase n”);
printf(“Please enter 3 so a, b, c:”);
printf(“\na =”); scanf(“%d”, &the);
printf(“b =”); scanf(“%d”, &b);
printf(“c =”); scanf(“%d”, &c);
int denta = b*b – 4*a*c;
if (Denta > 0){
printf(“Equation 2 nghiem:”);
printf(“x = %.2f hoac x = %.2fn”, (-b + sqrt(Denta)) / (2*the), (-b – sqrt(Denta)) / (2*the));
}else{
if(Denta == 0){
printf(“Kep nghiem equation: x = %.2gn”, -b /2*a);
}else{
printf(“The equation has no solution n”);
}
}
system (“pause”);
return 0;
}
according to his, if its for a = 0 is not the experience for delta = b ^ 2 >= 0 so it will calculate the underlying pattern will form a, which form = 0 is wrong. Therefore, bạn nên đặt điều kiện cho a phải khác 0, nếu không thì cũng sai yêu cầu bài toán vì họ yêu cầu mình giải phương trình bậc 2.
theo mình biết thì bạn thiếu mất trường hợp a= 0
Hello,
anh có thể cho em hỏi mục “TUT basic C” ở bên phải anh dùng plugin gì không ạ 😀 Nó phân bài theo series khá hay.
Thank you.
Of, mình tự code thêm để nó thành 1 loạt bài theo mình chỉ định 🙂
Subscription galvanometer: 1000e / month
The electricity usage per household: 50 KW for 230D / KW
If the excess amount <= 50KW, the pricing 480D / KW
If 50KW < the excess amount < 100KW is charged VND700 / K
If the excess amount <= 100KW then charged to 900 dong / KW
– He asked the military for Kids " If the excess amount is charged to 900 dong 100kW / Kw letter A?
They make the last line written out of it (should be> = 100) For on-line <100 already.
dinh muc la 50kW
k co gai tien sau dau
Write a program that electricity charges include the following range:
– Tiền thêu bao điện kế: 1000 e / month.
– Norms of use per household 50 Kw.
– Part pricing norms 450 DJ / kW.
– If the excess amount <= 50 kw, the ticket price calculated for this section is 700 e / kwh.
– If the level exceeds the 50 and smaller kw 100 kw, the ticket price calculated for this section is 910 e / kwh.
How to use an if else with strings DC sir, I run DC but also what type KQ out “Dung” zậy???
#include
int main ()
{
char* d;
printf(“Con gi sang in the bang 4 chan, noon cell state 2 chan, chiu in bang 3 chan?\n”);
scanf(“%with”,&d);
if(d=”con nguoi”)
{
printf(“Dung”);
}
else
{
printf(“Sai”);
}
return 0;
}
You see it this post: https://cachhoc.net/2014/12/16/lap-trinh-c-bai-8-chuoi-ky-tu-trong-c/
Shorter way is not it @@, done that look behold
#include
#include
int main ()
{
int thang;
printf(“Please enter a month “);
scanf(“%d”,&ladder);
switch(ladder)
{
case 1:printf(“Thang %d co 31 right”,ladder);
break;
case 3:printf(“Thang %d co 31 right”,ladder);
break;
case 5:printf(“Thang %d co 31 right”,ladder);
break;
case 7:printf(“Thang %d co 31 right”,ladder);
break;
case 8:printf(“Thang %d co 31 right”,ladder);
break;
case 10:printf(“Thang %d co 31 right”,ladder);
break;
case 12:printf(“Thang %d co 31 right”,ladder);
break;
case 4:printf(“Thang %d co 30 right”,ladder);
break;
case 6:printf(“Thang %d co 30 right”,ladder);
break;
case 9:printf(“Thang %d co 30 right”,ladder);
break;
case 11:printf(“Thang %d co 30 right”,ladder);
break;
case 2:printf(“Thang 2 co 29 right”);
break;
default:printf(“Elevator% d does not exist”,ladder);
}
_getch();
return 0;
}
there. Learn watch it.
This way you have more compact sir
#include
// Please enter a number that 1 the month of the year,
//print see how many days of the month.
int main()
{
int a;
printf(“Login Win “);
scanf(“%d”,&the);
switch(the)
{
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12: printf(“Co 31 right!”);
break;
case 4:case 6:case 9:case 11: printf(“Co 30 right!”);
break;
case 2: printf(“co 28 right”);
break;
}
return 0;
}
#include
int main()
{
int sodiensd,ten,sodiencu,sodienmoi;
int tientradinhmuc,tienvuotdinhmuc;
printf(“Clicking on the old look :”);
scanf(“%d”,&sodiencu);
printf(“Click dielectric”);
scanf(“%d”,&sodienmoi);
sodiensd = sodienmoi-sodiencu;
printf(“so dien you use for this month is% d n”,sodiensd);
if (sodiensd50&&sodiensd100&&sodiensd<=150)
{
thien = sodiensd * 700;
tientradinhmuc = sodiensd * 230;
tienvuotdinhmuc = ten-tientradinhmuc;
}
else
{
tien sodiensd = 900 *;
tientradinhmuc = sodiensd * 230;
tienvuotdinhmuc = ten-tientradinhmuc;
}
printf("tien dinh muc la %d \n tien vuot dinh muc la %d\n tong tien phai tra la%d \n",tientradinhmuc,tienvuotdinhmuc,ten);
return 0;
}
This is the post code 5 help people see sir
int main()
{
float a=10000; /*rental 1 How galvanometer * /
int b=230; /*nutrition 50wvoi electricity usage in 230D / kw */
float c; /*his with * /
float d; /*chi so moi * /
e float;
printf(“Clicking on the old and new index n”);
scanf(“%f%f”,&c,&d);
if(d-c<=50)
{
printf("chi so cu :%f",c);
printf("chi so moi: %f",d);
printf("tien tra dinh muc la:50KW voi gia 230d");
e = abs(d-c) * 480;
printf("tien tra vuot dinh muc: %fd",and);
printf("tong tien phai tra: %fd",e+230);
}
else if(50<(d-c)<100)
{
printf("chi so cu :%f",c);
printf("chi so moi: %f",d);
printf("tien tra dinh muc la:50KW voi gia 230d");
e = abs(d-c)*700;
printf("tien tra vuot dinh muc: %fd",and);
printf("tong tien phai tra: %fd",e+230);
}
else
{
printf("chi so cu :%f",c);
printf("chi so moi: %f",d);
printf("tien tra dinh muc la:50KW voi gia 230d");
e = abs(d-c)*900;
printf("tien tra vuot dinh muc: %fd",and);
printf("tong tien phai tra: %fd",e+230);
}
return 0;
}
Written if else, teachers see you have it wrong with households
#include
#include
int main()
{
float a, b;//with his, chi so moi
printf(“so dien cu va so dien moi”);
scanf(“%f%f”,&the,&b);
printf(“\ntien subscribers ke = 1000D”);
if(b-a<=50) printf("\ntong tien phai tra: %f", 230*(b-a));
else{
if(50<b-a<=100){
printf("\ntien tra dinh muc: 11.500");
printf("\nso tien vuot dinh muc: %f", 480*(b-a-50));
printf("\ntong so tien phai tra: %f", 50*230+480*(b-a-50)+1000);
}
else{
if(100<b-a<150){
printf("\ntien tra dinh muc: 11.500");
printf("\nso tien vuot dinh muc: %f", 480*50+700*(b-a-100));
printf("\ntong so tien tra: %f", 11.500+480*50+700*(b-a-100)+1000);
}
else{
if(150<=b-a){
printf("\ntien tra dinh muc: 11.500");
printf("\nso tien vuot dinh muc: %f", 480*50+700*50+900*(b-a-150));
printf("\ntong so tien phai tra: %f",11.500+480*50+700*50+900*(b-a-150)+1000);
}
}
}
}
return 0;
}
I ask you should learn C or C ++ before ạ ?
Previous school which was also nhé.
Yes, AD, Can you explain the principle of the operation of the switch-case?, I still do not understand 1 number of seats
+ Which command will it raise to a value and compare?
Hope you can help me, admin
switch-case has the same function as if-else. There is no increase command in switch-case.
What is the charge for the electricity meter subscription?
hope you explain
fee type for the meter.