Course Introduction to Programming
If-Else
In this lesson, we will learn what is and how to use the decision structure if-else. This lesson is divided into the following topics:
- Example of a problem
- Logical negation operator
- Structure if-else
Example of a problem
A student has a grade of
Consider that a student is approved if his or her grade is greater than or equal to
To solve this problem, we have the following 3 options:
- Make two if's: one checking if the grade is greater than or equal to
and another checking if it is less than .
if( x >= 7 ){ // checks if x is greater than or equal to 7
printf("Approved!");
}
if( x < 7 ){ // checks if x is less than 7
printf("Not Approved!");
}
Make two if's: one checking if the grade is greater than or equal to
and another checking if it is not greater than or equal to . Use the if-else structure.
Logic Negation Operator
To use the second option presented, we will need to learn what is and how to use the logical negation operator.
This operator can be used to check if a condition is false instead of true. In other words, it will reverse the value of the statement.
In C, the logical negation operator is represented by an exclamation point ("!"), and must come before the statement to be analyzed, following the template below:
if( ! condition ){ // check if condition is false
}
This way, to solve the exercise presented above by the second method, we will have the following code:
if( x >= 7 ){ // checks if x is greater than or equal to 7
printf("Approved!");
}
if( !( x >= 7 ) ){ // check if x is not greater than or equal to 7
printf("Not Approved!");
}
Observation: Note that the statement preceded by the logical negation operator was involved in parentheses. If we hadn't done this, then the logical value of
Structure if-else
To use the third option presented, we will need to learn what is and how to use the if-else structure.
It is a structure that specifies a code to be executed if a condition is true and another code if it is false.
This structure follows the template below:
if( condition ){
// True
}
else{
// False
}
In the above structure, the code block contained within if will only be executed if the condition is true. Meanwhile, the code block contained inside the else will only be executed if the condition analyzed by the if is false.
Therefore, we can read the code above as follows: "If this condition is true, execute this. If not, execute that".
This way, to solve the exercise presented above by the third method, we can write the code below:
if( x >= 7 ){ // checks if x is greater than or equal to 7
printf("Approved!");
}
else{ // if the above condition is false
printf("Not Approved!");
}
See you in the next class!