Course Introduction to Programming
Decision Structures
In this lesson, we will learn what are and how to use the relational operators and the if decision structure, addressing the following topics:
- Relational operators
- True or False
- IF decision structure
Relational operators
Relational operators are used to determine whether a relationship between two values is true or false.
Examples:
---> true ---> false
The main operators that will be used in C are represented in the table below:
Operator | Relationship |
---|---|
< | Less than |
> | Greater than |
<= | Less than or equal to |
>= | Greater than or equal to |
== | Equal to |
!= | Different |
Observations:
- The relation is always applied to compare the value on the left of the operator with the value on the right, in that order.
- Note that the relation of equality is expressed by an operator with two equal signs. This occurs because a single equal sign is used to assign values, as seen in past lessons.
True or False
In programming in general, the values of false and true are assigned to numbers. That is, if a certain comparison is true, then it will be worth
Knowing this, we can print the result of a comparison using the printf command:
printf("%d\n", 1 < 2);
printf("%d\n", 3 > 4);
/* Output:
1
0
*/
Notice that the output of the first command was
The output of the second command was
Decision structure IF
We can apply the relational operators above to create a decision structure based on the veracity of a statement. That is, if such a statement is true, execute a certain code.
This structure is the if, and does exactly what was said above. Its syntax is as follows:
if( condition ){
Code
}
Now let's explain what this statement means.
When the program reaches this structure, it will check if the statement/condition contained within the parentheses is true. If it is, then the code contained within the braces will be executed. Otherwise, this code will be ignored and the program will follow its execution after the braces.
Example:
if( 1 < 2 ){
printf("1 less than 2\n");
}
/* Output:
1 less than 2
*/
Note that since the
Observation: Notice that the comparison used resulted in
if(3){
printf("Value different from 0\n");
}
/* Output:
Value different from 0
*/
As
Taking into account all the knowledge obtained so far, we can create a program that reads a certain value
Before you continue reading, we recommend that you try to perform this task by yourself. In case you don't succeed, see below a way to do it:
#include <stdio.h>
int main(){
int x;
scanf("%d", &x);
if(x % 2 == 0){
printf("%d is even!\n", x);
}
if(x % 2 != 0){
printf("%d is odd!\n", x);
}
}
Explanation:
For a value to be even, the rest of its division by
It starts by declaring the variable
If this statement is true, the first printf will be executed.
Regardless of whether the condition in the first if is true or false, the second if will also be checked.
If
See you in the next class!