CodeBlanks Logo Icon CodeBlanks

Summary - Conditionals

Combine if, switch and ternary to write a day-of-week app.

Summary - Conditionals

In this group you learned five constructs that make your program behave differently in different situations: if, else/else if, switch, ternary and nested conditionals.

Now you will combine them in a day-of-week app. First you will print the day name with switch, then check weekday vs weekend with if/else. Such combined tasks appear all the time in menus, clocks and state machines.

Practice Day name (switch)

The day variable is set to 3. Use switch (day) so that in case 3 the program prints "Wednesday". Add a break too.

Starter code

main.cpp
#include <iostream>

int main() {
    int day = 3;
    // Print the day name with switch
    return 0;
}

Sample solution

main.cpp
#include <iostream>

int main() {
    int day = 3;
    switch (day) {
        case 3:
            std::cout << "Wednesday" << std::endl;
            break;
    }
    return 0;
}

Expected output

Wednesday

Practice Weekend check (if/else)

The day variable is set to 6. Use the condition if (day == 6 || day == 7) to check the weekend; print "Weekend" when true and "Weekday" when false.

Starter code

main.cpp
#include <iostream>

int main() {
    int day = 6;
    // Weekend check with if/else
    return 0;
}

Sample solution

main.cpp
#include <iostream>

int main() {
    int day = 6;
    if (day == 6 || day == 7) {
        std::cout << "Weekend" << std::endl;
    } else {
        std::cout << "Weekday" << std::endl;
    }
    return 0;
}

Expected output

Weekend

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Match each construct to its scenario

Term Meaning
if (x > 0) Single condition check
if/else if/else Multiple ranges
switch (day) Constant value pick
(a > b) ? a : b One-line pick

2 Which construct does one-line conditional assignment?

main.cpp
// one-line pick
  • if/else
  • ternary (? :) Correct answer
  • switch
  • for loop

Explanation: The ? : operator yields a conditional value in one line.

3 Write the ternary symbol

Question
int a = 7;
int b = 12;
int max = (a > b) ____ a : b;
Answer
int a = 7;
int b = 12;
int max = (a > b) ? a : b;

Explanation: The ? operator picks the left value when the condition is true.

All lessons in Beginner