ES101 - Lesson 4 : Conditional Statements

From Embedded Systems Learning Academy
Revision as of 00:58, 13 February 2013 by Preet (talk | contribs) (Branches and Operators)

Jump to: navigation, search

Branch Logic

The heart of any program lies in conditional logic. These are primarily if and else statements. Given below are the C conditional logic and examples that should serve as a good guide to completing this lab exercise.

Conditional statements are written using the if operator. The condition to evaluate is enclosed in parenthesis, and the code to execute for the evaluated condition should begin with a curly brace { and must end with a curly brace }. As long as the evaluation for the conditional statement is a non-zero number, then the conditional statement will execute its code. Let's first examine some of the conditional logic before we reveal their use in examples:

Operator Intended Operation
< Less than
> Greater than
<= Less than or equal to
>= Greater than or equal to
 != Not equal
== equals
&& AND
||
OR

Branches and Operators

int x = 123;
if(x >= 100) {
    puts("X is big!");
}
// else is optional, but we must have a preceding "if" statement to use it
else if(x > 50) {
    puts("X is small.");
}
// final else will cover anything that is not covered by if/else above
else {
    puts("X is really tiny.");
}


Individual conditions can be combined using AND and OR operators to form complex conditions. The following table shows some examples of this. With AND operator, all individual conditions must be true for the entire condition to be true. On the contrary, in the case of OR operator, any single condition that is true will cause the entire condition to be true.

int x = 100;
int y = 456;
if(x > 100 && y > 100) {
    puts("X and Y are both larger than 100");
}
if(x >= 100 || y >= 100) {
    puts("Either X is big, or Y is big, or both!");
}
if(x == 100 || y == 100) {
    puts("Either X or Y equals 100");
}
if(x == 100 || x == 101 || x == 102) {
    puts("X is either 100, 101 or 102");
}

// NOTICE A PITFALL!!!
if(x = y) {
    puts("X equals Y ???   NO!");
}
// To use "equals", you have to use "=="
if(x == y) {
    puts("This is more like it");
}


Integer Division & Modulus Operator

Another topic for this lesson is integer division. Remember that integers can only hold whole numbers, and this has a side-effect in some programming statements.

int score = 85;
int max_score = 100;

// Wrong result: percent_int will be zero:
// Since integers hold whole numbers, score/max_score = 0.85
// integer will be rounded down and percentage will be zero.
int percent_int = (score/max_score) * 100;

// Correct result: Tell compiler to use floating point division
float percent_float = ((float)score/max_score) * 100;

// Another method would be to declare score as float, then
// the compiler will carry out floating-point division.

One way to solve the problem is that when the division is taking place, the variable score can be temporarily converted to a floating point number as shown in the example. This lets the compiler use decimal numbers to carry out the multiplication and division. This temporary conversion is formally known as type casting and can be applied to other conversions as well. But even in this case, since percent is an integer, a whole number percent will be stored, such as 85, but not 85.5.

Another way to solve the problem is declare the variables as floating point in the beginning. This way, the variable percent can hold decimal numbers, such as 92.50, however, the downside is that it is very slow for a processor to work with floating-point numbers. Typically, a floating-point division can take several microseconds, while an integer division usually will take 100 times less time. In summary, you should only use the floating point numbers if absolutely necessary.

Modulus Operator

It should be observed that integer division only carries whole number result, for example, 5/10 is 0, and 15/10 is 1. This is where the % operator comes in, which can reveal the remainder of the result. Below are some examples:

int remainder = 0;
remainder = 3 % 10;  // remainder = 3
remainder = 89 % 10; // remainder = 9
remainder = 90 % 10; // remainder = 0

The modulus operator is more useful than just finding just the remainder. It is usually used to execute some portions of the code at certain intervals. For example, one could have a counter incrementing by 1, and using the modulus operator, you can take actions at every 10th increment of a variable by writing an if statement as: if( (counter%10) == 0)


Operator Precedence

Operator precedence for +, -, *, / describes the order of evaluation. Multiplication and division take precedence over addition or subtraction. Operators with the same precedence are evaluated from left-to-right. Parenthesis can be used to change and/or clarify the order of precedence, just as in math equations.

int my_int;
my_int = 1 * 2 + 3 * 2 / 1 - 3 + 2 * 3;

// Apply precedence rules:
my_int = (1 * 2) + (3 * 2 / 1) - 3 + (2 * 3);

// Simplify
my_int = 2 + 6 - 3 + 6;


Operator Shortcuts

You can also use shortcuts to use common techniques used in programming. See examples below

int x = 1;
x += 2; // same as x = x + 2
x -= 1; // same as x = x - 1
x /= 1; // same as x = x / 1
x *= 2; // same as x = x * 2

x++; // same as x = x+1
x--; // same as x = x-1


Assignment

  1. Ask the user about the score they received on a midterm.
    • Store this to a variable
  2. Ask the user how much the maximum possible score.
    • Store this to a variable
  3. Calculate the percentage and display it on the screen.
    • Store this to a variable
  4. Calculate the grade letter, store it to a variable, and display it on the screen.
    • Hint: Use if and else if statements. Scan from A to D leaving F to else statement.
  5. If the user's grade is either B, C, or D, display on the screen how much was the user away from the next letter grade.
    • Hint: (Score % 10) will tell you the remainder. If grade is B, C or D, calculate the remainder and subtract from 10.
    • Example: "You scored a B, and you were 3 points away from next letter grade."
  6. Use if statements to validate user inputs. For example, score received should not be more than maximum possible score.
    • You can restart the program if user enters invalid input by pressing the RESET button on the processor board.

Sample Code

int main(void)
{
    float percent = 0;
    printf("Enter your percentage: ");
    scanf("%f", &percent);
 
    char grade_letter = 'F';
    if(percent >= 90) {
        grade_letter = 'A';
    }
    else if(percent >= 80) {
        grade_letter = 'B';
    }
    else {
        grade_letter = 'U'; // Unknown, you do the rest :)
    }

    printf("Based on %u%%, your grade letter is: %c\n", percent, grade_letter);

    return -1;
}


Questions

  • Determine the output of the following program:
if(-1) {
    puts("Negative one!");
} 
if(0) {
    puts("Zero!");
}