Ternary conditional operator, while statement#
Ternary conditional operator :?#
This is short-hand if-else:
condition ? consequent : alternative;
or in other words:
is this condition true ? [if yes, return this] : [if no, return this]
Example#
Example based on the test code of the previous Lunar Lander Control code. The code tests whether the behavior of the lunar lander control is correct dependent on the altitude and thruster values.
#include <stdio.h>
int main() {
// Assume values
auto altitude = 20;
auto thruster = true;
bool behaviorCorrect = (altitude > 100 && thruster == 0) ||
(altitude <= 100 && altitude > 0 && thruster == 1) ||
(altitude <= 0 && thruster == 0);
char *behaviorCorrectIcon = behaviorCorrect ? "✅" : "❌";
// ?: operator saves an if-else statement
printf("For altitude %3d, your thruster is %d |%s|\n", altitude, thruster,
behaviorCorrectMessage);
}
Activity 18
Copy the code above and convert the ternary conditional operator to a if-else statement.
Steps:
3 min individually
while statement#
Repeating an operation in a fast manner is a superpower of a computer. while repeats a block of operations as long as the given condition is true.
#include <stdio.h>
int main() {
auto solution = 84;
puts("Guess the number! Enter:");
int guess;
scanf("%d", &guess);
while (solution != guess) {
printf("Is ");
puts(solution > guess ? "higher " : "lower");
puts("Try again:");
scanf("%d", &guess);
}
printf("🎉 Congratulations");
}
Question to ponder
How can we represent a while loop in a flowchart?
How can we represent a
while(True)in a flowchart?How can we break free of a
while(True)?