Ternary conditional operator, while statement

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 *behaviorCorrectMessage = behaviorCorrect ? " OK " : "FAIL";
  // ?: 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
  1. How can we represent a while loop in a flowchart?

  2. How can we represent a while(True) in a flowchart?

  3. How can we break free of a while(True)?

Going back to the problem#

Now use your fresh knowledge on the previous coding problem that we did not finish.

Activity 19

Now go back to Activity 11 again and continue/improve your solution.

Try to separate data and program logic.

Optional: First write a version without data and logic separation, then with.

Process:

  • 10min individual