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.

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

The if statement

Syntax, flowcharts, and how the 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

Lệnh if else

Syntax, flowcharts, and how it works if statement – 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

A switch case

Syntax, flowcharts and operating switch case

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:

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

  2. Please enter a number that 1 the month of the year, print see how many days of the month. (Regarded as no leap year).

  3. Let programmers program the quadratic equation 2: ax^{2} + bx + c = 0 with a, b, c typing.

  4. 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:

    S = \sqrt{p(p-a)(p-b)(p-c)} where p is half the perimeter of the triangle. p = \frac{a+b+c}{2}

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