0
0
C++programming~10 mins

Ternary operator in C++ - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to assign the smaller of two numbers to min using the ternary operator.

C++
int a = 10, b = 20;
int min = (a < b) ? a : [1];
Drag options to blanks, or click blank then click option'
Ab
Ba
C10
D20
Attempts:
3 left
💡 Hint
Common Mistakes
Using the wrong variable after the colon.
Forgetting the colon in the ternary operator.
2fill in blank
medium

Complete the code to assign result to "Even" or "Odd" based on the value of num.

C++
int num = 7;
std::string result = (num % 2 == 0) ? "Even" : [1];
Drag options to blanks, or click blank then click option'
A"Odd"
B"even"
C"odd"
D"Odd number"
Attempts:
3 left
💡 Hint
Common Mistakes
Using lowercase "odd" instead of "Odd".
Using a phrase like "Odd number" instead of "Odd".
3fill in blank
hard

Fix the error in the ternary operator expression to correctly assign the absolute value of x to absVal.

C++
int x = -5;
int absVal = x >= 0 ? x [1] -x;
Drag options to blanks, or click blank then click option'
A,
B;
C?
D:
Attempts:
3 left
💡 Hint
Common Mistakes
Using a semicolon or comma instead of a colon.
Omitting the colon entirely.
4fill in blank
hard

Fill both blanks to create a ternary operator that assigns grade "Pass" if score is 50 or more, otherwise "Fail".

C++
int score = 65;
std::string grade = (score [1] 50) ? "Pass" : [2];
Drag options to blanks, or click blank then click option'
A>=
B<
C"Fail"
D"fail"
Attempts:
3 left
💡 Hint
Common Mistakes
Using '<' instead of '>=' for the condition.
Using lowercase "fail" instead of "Fail".
5fill in blank
hard

Fill all three blanks to create a nested ternary operator that assigns category based on age: "Child" if under 13, "Teen" if 13 to 19, otherwise "Adult".

C++
int age = 15;
std::string category = (age < [1]) ? "Child" : ((age [2] 19) ? "Teen" : [3]);
Drag options to blanks, or click blank then click option'
A13
B<=
C"Adult"
D20
Attempts:
3 left
💡 Hint
Common Mistakes
Using wrong age limits or comparison operators.
Forgetting to quote the string "Adult".