Logic Control

Operators for Testing Relations and Equality

< less than
> greater than
<= less than or equal to
>= greater than or equal to
== equal to
!= not equal to

Logical Operators

  1. && (and)
    Truth Table
    var1 var2 var1 && var2
    0 0 0
    0 1 0
    1 0 0
    1 1 1

  2. || (or)
    Truth Table
    var1 var2 var1 || var2
    0 0 0
    0 1 1
    1 0 1
    1 1 1

  3. ! (not)
    Truth Table
    var1 !var1
    nonzero 0
    0 1

The if statement

  1. An if statement
    Example:
    if (x == 2)
        printf("x is equal to 2.\n");
    

  2. A compound if statement
    Example:
    if (x == 2)
    {
        printf("x is equal to 2.\n");
        x = x + 6;
    }
    
    

  3. An if statement with two alternatives
    Example:
    if (x == 2)
        printf("x is equal to 2.\n");
    else
        printf("x is not 2.\n");
    

  4. An if statement with more than 2 alternatives
    Example:
    if (x == 2)
        printf("x is equal to 2.\n");
    else if (x == 3)
        printf("x is three!\n");
    else
        printf("x isn't two or three.\n");
    
    

The Switch Statement

Used to select between several alternatives based on the value of a variable or expression. The argument must be of type int or char. The result of the following example program will be "numbr is twelve" printed to the screen.


#include <stdio.h>

int main() {

    int numbr;

    numbr = 12;

    switch(numbr) {
    
    case 2:
        printf("numbr is two");
	break;
    
    case 7:
        printf("numbr is seven");
	break;

    case 12:
        printf("numbr is twelve");
	break;

    default:
        printf("numbr is something else");
    }

    return 0;

}
Source File | DOS Executable (run from DOS prompt)