Basic structures: Conditions

Below I will list a number of basic structures: Conditions and loops in a variety of realizations.
  • Simple Conditions:
    ...
        if (statement == true) {
            things to be done;
        }
    ...

    A few things are to be noted here:
    • Within the round brackets is the statement to be checked. It is of the type boolean, i.e. 0 or 1, (false or true). In case it is true, the body of the condition within the curly brackets will be executed. In case the body consists of exactly one command, you can omit the curly brackets. In other words, the curly brackets, cluster a list of commands, assignments, etc. such that they are treated as one.
    • For the statement to be checked you will have expressions like a == b, a != b, a > b, a <= b. It is important to use two equal signs, remember that we don't do maths here. One equal sign is an assignment, two such signs represent a check of the identity. For a computer this is not the same, so this is just a syntax question to have two different operators.
    • Beyond comparison of two things (equal, larger, smaller etc.) you can also connect such statements to be checked, i.e. there are also logical operators like:
      • ! denotes a negation (NOT statement).
      • && denotes an AND statement.
      • || denotes an OR statement.
      The important thing to keep in mind is to cluster these statements in a sensible way. For this you use round brackets. As a hint: Use them in abundance.
  • Simple conditions with alternatives:
    ...
        if (statement == true) {
            things to be done;
        }
        else {
            other things to be done;
        }
    ...

    I guess this is quite obvious. however, note that you can nest these things, i.e. you are allowed to have a new set of if-statements within your things to be done. This allows for the construction of a hierarchy of conditionals.
    You could also do something like:
    ...
        if (statement_1 == true) {
            things to be done;
        }
        else if (statement_2 == true) {
            other things to be done;
        }
        else if (statement_3 == true) {
            yet other things to be done;
        }
        else {
            yet other things to be done;
        }
    ...

  • Selection from a list:
    ...
        switch (integer) {
            case 0: { things to be done;break;}
            case 1: { other things to be done;break;}
            case 2: { yet other things to be done;break;}
            ...
            default: { yet other things to be done;}
        }
    ...

    Subsequently the integer is compared with the values after "case". In case a match occurs, the statements are executed and the selection routing is left with break; . This is important because the last (optional) statement default is executed whenever it is reached.

    [prev] [top] [next]