Sunday, May 20, 2012

Logic and Conditions in C

    In C, logic allow your commands to change if certain conditions are met, making them a bit smarter.  This tutorial will attempt to discuss how to use the logic found in C.  It will cover the if statement, logic operators, and the switch statement.

If and else statements:
    The most common way to use logic is the if statement.  This is present in other languages as well, but the syntax in C is "if (logic test) {commands;}".  The terms "logic test" and "commands" are replaced with your own code in this case.  Commands can be functions, arithmetic, printing, waiting, etc.

    The logic test will be either true or false.  If is is true, the commands will be executed; but if it is false, the commands are skipped entirely.  In order to create a statement which is true or false for numbers, use the following comparison tests: is equal to, is not equal to, is less than, is greater than, is less than or equal to, is greater than or equal to.

    These are comparison operators in C: ==, !=, <, >, <=, >= (listed in same order as mentioned before).  They require a number on both sides and give a true or false result.  For example, 5 == 7 gives us false, but 5 != 7 is true.  The following example shows how to use the if statement:
#include <stdio.h>

//wait_key prototype
int wait_key();

int main() {
    int x = 7, y = 5;

    if (x > y) {
        printf("x > y");
    }
    else {
        printf("x <= y");
    }

    return wait_key();
}

//wait_key definition
int wait_key() {
    getchar();
    return 0;
}
output in prompt:
x > y

    Here, x is greater than y and the command printf("x > y"); is performed.  However, the command printf("x <= y"); does not occur because the comparison test was true.  This is not all to this example though; if you were change the value of x to 3 and y to 8, the output would say x <= y.

    Else means the opposite of the comparison test.  If x is not greater than y, x can only be less than or equal to y.  In this case, else could have been replaced with if (x <= y) since > and <= are opposite tests.  < and >= are opposites tests too, as well as the == and != operators.

    If and else allow commands for two cases: the comparison and its opposite, but what about functions where three or more possibilities can occur?  For example, what about a function that says if input is 3 or 7 or another number?  The following example shows a function that does just that:
#include <stdio.h>

//wait_key prototype
int wait_key();

void checkInt(int input) {
    if (input == 3) {
        printf("input is 3\n");
    }
    else if (input == 7) {
        printf("input is 7\n");
    }
    else {printf("input not 3 nor 7\n");}
}

int main() {
    int a = 3, b = 5, c = 7;

    checkInt(a);
    checkInt(b);
    checkInt(c);

    return wait_key();
}

//wait_key definition
int wait_key() {
    getchar();
    return 0;
}
output in prompt:
input is 3
input not 3 nor 7
input is 7


    The keyword "else if" is the equivalent of another if statement.  The reason I do not just use if is that "else if" affects else: now else is for cases where input != 3 and input != 7.  The else statement has become more complex, but can still be replaced with an if statement.

Logical operators:
    To make logic more interesting, C has operators which use comparison tests as input and output true or false.  They can be placed inside an if statement to account for more possibilities.  The operators are logical and(&&), logical or(||), and logical not(!).

    The logical and and or operators use symbols similar to bitwise and and or.  This is no coincidence: the logical operators treat true as a 1 bit and false as 0.  Here is a table to show how logical or and and work:
comparison testcomparison testlogical and(&&)logical or(||)
(5 == 7) false(5 == 7) falsefalsefalse
(5 == 7) false(5 == 5) truefalsetrue
(5 == 5) true(5 == 7) falsefalsetrue
(5 == 5) true(5 == 5) truetruetrue


    To clarify, the commands within if ((5 == 7) && (5 == 5)) { will never be executed.  This table is very similar to the bitwise table from the operators post, http://multimediaprogram.blogspot.com/2012/05/c-operators.html, except that there is no logical xor.

    Logical not works much like bitwise not: !(5 == 5) is false and !(5 == 7) is true.  In fact, !(5 == 5) is the equivalent of (5 != 5).  The comparison test becomes the opposite, so !(x > y) becomes (x <= y).

    Here is an example of how to use these operators effectively: if ((x != 3) && (x != 7)) { can replace the else statement from the previous code example.  This is not limited to equalities though, you can also test if a number is within a certain range:
#include <stdio.h>

//wait_key prototype
int wait_key();

void checkRange(int input) {
    if (input > 0 && input <= 10) {
        printf("input is 1 to 10\n");
    }
    else {
        printf("input is not 1 to 10\n");
    }
}

int main() {
    int a = -1, b = 5, c = 7;

    checkRange(a);
    checkRange(b);
    checkRange(c);

    return wait_key();
}

//wait_key definition
int wait_key() {
    getchar();
    return 0;
}
output in prompt:
input is not 1 to 10
input is 1 to 10
input is 1 to 10


    The function checkRange will tell us whether a number is within the range 1 to 10.  This is accomplished with two comparison tests and logical and.  The else statement for this example would be if (!(input > 0 && input <= 10)) { which can also be if (input <= 0 || input > 10) { since these two are logically the same.

Switch statement:
    The last concept of logic to discuss is a switch statement.  The logic is pretty tame, but the written style can be messy.  The format starts with switch (variable) {, where variable is any variable you choose.  Next, there is case value:, where value is any value, which is followed by commands.

    One way to use this statement is to revisit the checkInt function, which checks for input equal to 3 or 7 or something else:
#include <stdio.h>

//wait_key prototype
int wait_key();

void checkInt(int input) {
    switch (input) {
    case 3: //if (input == 3)
        printf("input is 3\n");
        break;
    case 7: //else if (input == 7)
        printf("input is 7\n");
        break;
    default: //else
        printf("input not 3 nor 7\n");
        break;
    }
}

int main() {
    int a = 3, b = 5, c = 7;

    checkInt(a);
    checkInt(b);
    checkInt(c);

    return wait_key();
}

//wait_key definition
int wait_key() {
    getchar();
    return 0;
}
output in prompt:
input is 3
input not 3 nor 7
input is 7



    The goal of this example is to show that this checkInt and the previous version perform the same task.  The if, else if, and else are included as comments here, so they are not part of the switch statement.  These comments attempt show that the first case is basically the if statement if (variable == value) {.  Any additional cases are the else if statement else if (variable == value) {.

    Finally, default is the equivalent of else.  Each case performs similar commands found in the original checkInt, but with the added break command.  Break is a command which exits the switch statement after the commands of a case are performed and is necessary for a proper switch statement.

    For more information about the switch statement, check out the C programming tutorial http://www.cprogramming.com/tutorial/lesson5.html.  For more about if and logic, try the page http://www.cs.utah.edu/~zachary/computing/lessons/uces-11/uces-11/node9.html.

    The next tutorial will cover loops (with more examples of break).

No comments:

Post a Comment