tags:
- compsci/COMP1511/1
topic: C
date: 2024-01-03
icon: TiCode
Relational Operators
Relational operators can be used to determine the relationship between two variables, returning True
or False
dependant on the relationship.
Operator | Description |
---|---|
< | less than |
> | more than |
<= | less than or equal to |
>= | greater than or equal to |
== | equals |
!= | not equal to |
Conditional statements operate on a condition, and are more broadly known as 'if/while' statements. These conditions rely on relational operators.
Similar to Javascript, C's conditional statements are enclosed in brackets.
#include <stdio.h>
int main(void){
int myint;
scanf("%d", &myint);
if (myint > 5){ // conditional
printf("More than five!");
} else {
printf("Less than five!");
}
}
Note that else
statements directly following the closing parentheses of the if
statement, and contain parentheses of their own. This too happens with else if
(which cannot be last).
As (myint > 5)
does not take into account whether myint
is equal to 5, an else if
statement can be used to distinguish between less than, more than and equal to five.
#include <stdio.h>
int main(void){
int myint;
scanf("%d", &myint);
if (myint > 5){
printf("More than five!");
} else if (myint < 5) {
printf("Less than five!");
} else {
printf("Five!");
}
}
Code in this else if
will only run if the previous statements evaluate to False (again, 0 in C). Code in the else
will only run if all other conditions evaluate to False.
While statements run for the duration that something is True
.
Logical operators can be used to 'chain' conditions.
Operator | Meaning | Description |
---|---|---|
&& | AND | Returns True if both conditions are true. |
|| | OR | Returns True if any condition is true. |
! | NOT | Reverses the expression. |