Senin, 26 Oktober 2015

Decision Making / Branching in C

Decision / Branch in C

     Decision making is important concepts in c programming language. usually , program should be able to make logical or true/false decision based on the condition. the purpose of decision making/branch is to solve particular problems.
     Branching is the term given to the code executed in sequence as a result of change in the program flow. branching is the process of choosing the right branch for execution, depending on the result of the "statement condition".
     there are some syntax of decision making/branch. they are :
  1. If-else statement
    if the condition is true, the program will be executed. but if the condition expression is false, it will executed other statement.
    example :
    #include <stdio.h>
    int main ()
    int a = 5;
    if (a<10) {  // this will be check the statement condition
    printf ("this is true\n"); // if the condition true the result will print this
    }
    else {
    printf ("this is false\n"); // if the condition false the result will print this
    }
    return 0;
    }

    the result will be "this is true" because it's right that a less than 10 (a<10). that a = 5.
  2. Switch case statement
    switch case statement is used to make a selection towards expression or condition that have constant values. because of that, the expression that is defined must be produced a value of integer or character.
    example :
    #include <stdio.h>
    int main ()
    {
    int how_many_pet = 4;
    switch (how_many_pet) {
    case 5 : case 4 : case 3 : printf ("animallover"); break;
    case 2 : printf ("perfect"); break;
    case 1 : printf ("cool"); break;
    case 0 : printf ("miss"); break;
    default :
    printf ("butoklah");
    return 0;
    }
    }

    the result will be "animallover".
  3. Ternary Operator (?:)
    ternary operator can be used to replace if else statement. the general form :
    condition 1? condition 2 : condition 3
    if condition 1 is true, then condition 2 is evaluated and becomes the value of the expression. but if condition 1 is false, then condition 3 is evaluated and becomes the value of the expression.
    example :
    #include <stdio.h>
    int main ()
    {
    int love = 100;
    int match = (love>100 ? 100 : 50);
    if (love>100) {
    printf ("match = 100");
    }
    else
    {
    printf ("match = 50");
    }
    return 0;
    }

    the result will be "match = 50".

Tidak ada komentar:

Posting Komentar