Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to call the function foo.
C++
#include <iostream> void foo() { std::cout << "Hello from foo!" << std::endl; } int main() { [1]; return 0; }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Writing only the function name without parentheses.
Adding extra words like 'call' before the function name.
✗ Incorrect
To call a function in C++, you write its name followed by parentheses. So
foo() calls the function.2fill in blank
mediumComplete the code to make bar call foo.
C++
#include <iostream> void foo() { std::cout << "Inside foo" << std::endl; } void bar() { [1]; } int main() { bar(); return 0; }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Forgetting parentheses when calling the function.
Adding extra words like 'call' before the function name.
✗ Incorrect
Inside a function, to call another function, use its name with parentheses like
foo().3fill in blank
hardFix the error in the recursive function countdown to avoid infinite recursion.
C++
#include <iostream> void countdown(int n) { if (n == 0) { std::cout << "Done!" << std::endl; return; } std::cout << n << std::endl; countdown([1]); } int main() { countdown(3); return 0; }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Calling with the same number causing infinite recursion.
Increasing the number instead of decreasing.
✗ Incorrect
To count down, you need to call
countdown with n - 1 so the number decreases each time.4fill in blank
hardFill both blanks to create a dictionary-like map of numbers to their squares using a loop.
C++
#include <iostream> #include <map> int main() { std::map<int, int> squares; for (int [1] = 1; [2] <= 5; ++i) { squares[i] = i * i; } for (const auto& [key, value] : squares) { std::cout << key << ": " << value << std::endl; } return 0; }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using different variable names in initialization and condition.
Using variables not declared in the loop.
✗ Incorrect
The loop variable should be the same in initialization and condition. Here,
i is used.5fill in blank
hardFill all three blanks to create a recursive function that sums numbers from n down to 1.
C++
#include <iostream> int sum_to_n(int [1]) { if ([2] == 0) { return 0; } return [3] + sum_to_n([2] - 1); } int main() { std::cout << sum_to_n(5) << std::endl; return 0; }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using different variable names causing errors.
Forgetting to decrease the number in the recursive call.
✗ Incorrect
The function parameter and recursive calls use the same variable
n to sum down to zero.