Difference between revisions of "ES101 - Lesson 4 : Conditional Statements"

From Embedded Systems Learning Academy
Jump to: navigation, search
(Assignment)
(Assignment)
 
(12 intermediate revisions by the same user not shown)
Line 38: Line 38:
 
int x = 123;
 
int x = 123;
 
if(x >= 100) {
 
if(x >= 100) {
 +
    // puts() is the same thing as printf() with automatic \n.
 +
    // puts() doesn't understand %i %f etc.
 
     puts("X is big!");
 
     puts("X is big!");
 
}
 
}
// else is optional, but must have an if to use and else if
+
// else is optional, but we must have a preceding "if" statement to use it
 
else if(x > 50) {
 
else if(x > 50) {
 
     puts("X is small.");
 
     puts("X is small.");
Line 116: Line 118:
 
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: <code>if( (counter%10) == 0)</code>
 
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: <code>if( (counter%10) == 0)</code>
  
<br/>
+
'''Note that you can only use the % operator with integers (not floats).'''  If you happen to have a floating point number, you can cast it to integer to take the modulus operator result. See below for example :
== 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.
 
 
<syntaxhighlight lang="c">
 
<syntaxhighlight lang="c">
int my_int;
+
float percent = 75;
my_int = 1 * 2 + 3 * 2 / 1 - 3 + 2 * 3;
+
int remainder = (int)percent % 10; ///< Remainder will be 5
 +
</syntaxhighlight>
  
// Apply precedence rules:
+
<br/>
my_int = (1 * 2) + (3 * 2 / 1) - 3 + (2 * 3);
 
  
// Simplify
+
== Assignment ==
my_int = 2 + 6 - 3 + 6;
+
#  Declare the following float variables :
</syntaxhighlight>
+
#*  Maximum exam score, user's exam score, and percentage.
 +
#  Ask the user to input data into your variables, such as:
 +
#*  "What is the max score of your exam: "
 +
#*  "What was your score: "
 +
#  Use if statements to validate user inputs. For example, score received should not be more than maximum possible score.
 +
#*  Display an error message when the user enters invalid data.
 +
#*  You can restart the program if user enters invalid input by pressing the RESET button on the processor board.
 +
#  Build your Software logic to calculate the percentage and the letter grade.
 +
#*  Hint: Store your letter grade to a char variable.
 +
#*  Hint: Use '''if''' and '''else if''' statements. Scan from A to D leaving F to '''else''' statement.
 +
#  Print out summary for the user :
 +
#* If the user's grade is either B, C, or D, print-out how many percent points the user is 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 print-out:
 +
#*: '''"You scored a B, and you were 3 percent away from next letter grade."'''
  
<br/>
+
=== Sample Code ===
== Operator Shortcuts ==
 
You can also use shortcuts to use common techniques used in programming.  See examples below
 
 
<syntaxhighlight lang="c">
 
<syntaxhighlight lang="c">
int x = 1;
+
int main(void)
x += 2; // same as x = x + 2
+
{
x -= 1; // same as x = x - 1
+
    float score = 0;
x /= 1; // same as x = x / 1
+
    printf("Enter your score: ");
x *= 2; // same as x = x * 2
+
    scanf("%f", &score);
 +
 +
    char grade_letter = 'F';
 +
    if(score >= 90) {
 +
        grade_letter = 'A';
 +
    }
 +
    else if(score >= 80) {
 +
        grade_letter = 'B';
 +
    }
 +
    else {
 +
        grade_letter = 'U'; // Unknown, you do the rest :)
 +
    }
  
x++; // same as x = x+1
+
    printf("Based on %u%%, your grade letter is: %c\n", score, grade_letter);
x--; // same as x = x-1
+
 
 +
    return -1;
 +
}
 
</syntaxhighlight>
 
</syntaxhighlight>
 
<br/>
 
== Assignment ==
 
# Ask the user about the score they received on a midterm.
 
#*  Store this to a variable
 
# Ask the user how much the maximum possible score.
 
#*  Store this to a variable
 
# Calculate the percentage and display it on the screen.
 
#*  Store this to a variable
 
# 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.
 
#  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. You can only use a single if statement for this requirement.
 
#*  Hint: You can use the % Operator to find out if the grade % 10 is equal to 9.
 
#  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.
 
  
 
<br/>
 
<br/>
  
 
== Questions ==
 
== Questions ==
*  Determine the output of the following program:
+
*  Determine which if statements will execute and why?
 
<syntaxhighlight lang="c">
 
<syntaxhighlight lang="c">
 
if(-1) {
 
if(-1) {
     puts("Negative one!");
+
     puts("1.  Will this print?");
 
}  
 
}  
 
if(0) {
 
if(0) {
     puts("Zero!");
+
     puts("2.  Will this print?");
 
}
 
}
 
</syntaxhighlight>
 
</syntaxhighlight>

Latest revision as of 22:20, 17 September 2013

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() is the same thing as printf() with automatic \n.
    // puts() doesn't understand %i %f etc.
    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)

Note that you can only use the % operator with integers (not floats). If you happen to have a floating point number, you can cast it to integer to take the modulus operator result. See below for example :

float percent = 75;
int remainder = (int)percent % 10; ///< Remainder will be 5


Assignment

  1. Declare the following float variables :
    • Maximum exam score, user's exam score, and percentage.
  2. Ask the user to input data into your variables, such as:
    • "What is the max score of your exam: "
    • "What was your score: "
  3. Use if statements to validate user inputs. For example, score received should not be more than maximum possible score.
    • Display an error message when the user enters invalid data.
    • You can restart the program if user enters invalid input by pressing the RESET button on the processor board.
  4. Build your Software logic to calculate the percentage and the letter grade.
    • Hint: Store your letter grade to a char variable.
    • Hint: Use if and else if statements. Scan from A to D leaving F to else statement.
  5. Print out summary for the user :
    • If the user's grade is either B, C, or D, print-out how many percent points the user is 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 print-out:
      "You scored a B, and you were 3 percent away from next letter grade."

Sample Code

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

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

    return -1;
}


Questions

  • Determine which if statements will execute and why?
if(-1) {
    puts("1.  Will this print?");
} 
if(0) {
    puts("2.  Will this print?");
}