Challenge - 5 Problems
Function Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of code using functions for reuse
What is the output of this C++ code that uses a function to add two numbers?
C++
#include <iostream> using namespace std; int add(int a, int b) { return a + b; } int main() { cout << add(3, 4) << endl; cout << add(10, 20) << endl; return 0; }
Attempts:
2 left
💡 Hint
Look at what the add function returns and how cout prints it.
✗ Incorrect
The function add returns the sum of two integers. The main function calls add twice and prints the results on separate lines.
🧠 Conceptual
intermediate1:30remaining
Why use functions in programming?
Which of the following is the main reason programmers use functions?
Attempts:
2 left
💡 Hint
Think about how functions help avoid writing the same code again and again.
✗ Incorrect
Functions allow programmers to write a piece of code once and reuse it multiple times, making programs shorter and easier to maintain.
❓ Predict Output
advanced2:00remaining
Output of code demonstrating function parameters and scope
What is the output of this C++ program that uses a function to modify a local variable?
C++
#include <iostream> using namespace std; void changeValue(int x) { x = 100; } int main() { int a = 10; changeValue(a); cout << a << endl; return 0; }
Attempts:
2 left
💡 Hint
Remember that function parameters are passed by value by default in C++.
✗ Incorrect
The function changeValue changes its local copy of x, but does not affect the variable a in main, so a remains 10.
❓ Predict Output
advanced1:30remaining
Output of code using function to avoid repetition
What will this C++ program print when run?
C++
#include <iostream> using namespace std; void printHello() { cout << "Hello!" << endl; } int main() { printHello(); printHello(); printHello(); return 0; }
Attempts:
2 left
💡 Hint
Each call to printHello prints one line with Hello!
✗ Incorrect
The function printHello prints "Hello!" followed by a newline. It is called three times, so three lines are printed.
🧠 Conceptual
expert2:00remaining
Why functions improve program structure
Which statement best explains how functions improve the structure of a program?
Attempts:
2 left
💡 Hint
Think about how dividing work into smaller pieces helps with understanding.
✗ Incorrect
Functions divide a program into smaller, manageable pieces. This makes the program easier to read, test, and fix.