Challenge - 5 Problems
Switch Statement Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of a simple switch statement
What is the output of this R code using
switch?R Programming
result <- switch("b", a = 1, b = 2, c = 3) print(result)
Attempts:
2 left
💡 Hint
Remember that
switch matches the first argument to the names.✗ Incorrect
The switch matches the string "b" to the named argument b = 2, so it returns 2.
❓ Predict Output
intermediate2:00remaining
Switch with numeric index
What will this R code print?
R Programming
result <- switch(3, "apple", "banana", "cherry", "date") print(result)
Attempts:
2 left
💡 Hint
When the first argument is a number,
switch returns the element at that position.✗ Incorrect
The number 3 selects the third element, which is "cherry".
🔧 Debug
advanced2:00remaining
Error in switch with unnamed arguments
What error does this R code produce?
R Programming
result <- switch("x", "apple", "banana", "cherry") print(result)
Attempts:
2 left
💡 Hint
If the first argument is a string but no matching name exists, what does switch return?
✗ Incorrect
When the first argument is a string and no matching name is found, switch returns NULL without error.
❓ Predict Output
advanced2:00remaining
Switch with expression and default
What is the output of this R code?
R Programming
x <- "z" result <- switch(x, a = 10, b = 20, c = 30, 40) print(result)
Attempts:
2 left
💡 Hint
If no named match is found, switch returns the last unnamed argument as default.
✗ Incorrect
Since "z" does not match a, b, or c, switch returns the last unnamed argument 40.
🧠 Conceptual
expert2:00remaining
Behavior of switch with numeric zero
What happens when you run this R code?
R Programming
result <- switch(0, "apple", "banana", "cherry") print(result)
Attempts:
2 left
💡 Hint
Check how switch treats numeric indices outside the valid range.
✗ Incorrect
Numeric indices less than 1 or greater than the number of options cause switch to return NULL.