ES101 - Lesson 4 : Conditional Statements
Contents
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
- Declare the following float variables :
- 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."
- 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.
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?");
}