0
0
C++programming~20 mins

Why functions are needed in C++ - Challenge Your Understanding

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Function Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2: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;
}
A7\n30
B34\n1020
C7 30
DCompilation error
Attempts:
2 left
💡 Hint
Look at what the add function returns and how cout prints it.
🧠 Conceptual
intermediate
1:30remaining
Why use functions in programming?
Which of the following is the main reason programmers use functions?
ATo make the program run faster by skipping code
BTo make the program use more memory
CTo repeat the same code many times without rewriting it
DTo confuse other programmers
Attempts:
2 left
💡 Hint
Think about how functions help avoid writing the same code again and again.
Predict Output
advanced
2: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;
}
A0
B100
CCompilation error
D10
Attempts:
2 left
💡 Hint
Remember that function parameters are passed by value by default in C++.
Predict Output
advanced
1: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;
}
AHello!\nHello!\nHello!
BHello! Hello! Hello!
CHello!\nHello!\nHello!\nHello!
DCompilation error
Attempts:
2 left
💡 Hint
Each call to printHello prints one line with Hello!
🧠 Conceptual
expert
2:00remaining
Why functions improve program structure
Which statement best explains how functions improve the structure of a program?
AFunctions increase the size of the program to make it more complex
BFunctions break a program into smaller parts, making it easier to understand and fix
CFunctions make programs run faster by skipping unnecessary code
DFunctions prevent the program from running if there is an error
Attempts:
2 left
💡 Hint
Think about how dividing work into smaller pieces helps with understanding.