APS105 L06 - If Statements
#APS105 Slides Lecture Link to web notes
If statements:
if (expression) {
statement; // only runs if expression is True
}
The relational operators in C are the same as in Python
e.g. == is equivalent to = in Math, or == in Python
If both operands are int, C will do the operation with exclusively int
If one or both of the operands are double, then C will perform the operation as a double.
Example:
if (2 == 2.0) {
printf("This part runs");
}
Logical operators:
|| means logical or
If left side and right side are true OR false, then 0 returned, but if only one side is true, then 1 is returned.
Same as or in Python.
&& means logical and (same as in Javascript)
! means logical not, flips the value (same as in Python)
Full example:
#include <stdio.h>
#include <stdlib.h>
int main(void) {
printf("Input an integer: ");
int num = 0;
scanf("%d", &num);
if (num % 2 == 0) { // if num % 2 == 0, then this printf runs
printf("The number is even!\n");
}
else {
printf("Number is not even\n"); // otherwise, prints this thing
}
return EXIT_SUCCESS;
}
Another full example:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(void) {
srand(time(NULL)); // uses the current timestamp as random seed
printf("Enter your bet, even or odd? (0 for even, 1 for odd): ");
int bet;
scanf("%d", &bet);
int dice = rand() % 6 + 1; // returns random num from 1 to 6 inclusive
printf("Rolled a %d\n", dice);
if (dice % 2 == bet) {
printf("You win!\n");
}
else {
printf("You lose!\n");
}
return 0;
}
Example of casting:
#include <stdio.h>
int main(void) {
if (0.4) {
printf("The number is true"); // this part runs
}
else {
printf("The number is false"); // this part doesn't run
}
}
The only way for C to interpret something as False through casting is if 0.000... is returned. Otherwise, the expression will be true.
Else if in C
#include <stdio.h>
int main(void) {
if (0.4 == 1) {
printf("The number is 1");
}
else if (0.4 == 2) {
printf("The number is 2");
}
else {
printf("The number is not equal to 1 or 2");
}
}