0
0
C++programming~20 mins

Return values in C++ - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Return Value Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
What is the output of this function call?
Consider the following C++ code. What will be printed when foo() is called?
C++
#include <iostream>

int foo() {
    int x = 5;
    return x + 3;
}

int main() {
    std::cout << foo() << std::endl;
    return 0;
}
A0
B5
CCompilation error
D8
Attempts:
2 left
💡 Hint
Remember the function returns the value of x plus 3.
Predict Output
intermediate
2:00remaining
What does this function return?
What is the return value of bar(4) in the following code?
C++
#include <iostream>

int bar(int n) {
    if (n <= 1) return 1;
    return n * bar(n - 1);
}

int main() {
    std::cout << bar(4) << std::endl;
    return 0;
}
A24
B10
C1
DCompilation error
Attempts:
2 left
💡 Hint
This function calculates the factorial of n.
Predict Output
advanced
2:00remaining
What is the output of this code with multiple return statements?
What will be printed when test() is called?
C++
#include <iostream>

int test() {
    for (int i = 0; i < 3; i++) {
        if (i == 1) return i;
    }
    return 10;
}

int main() {
    std::cout << test() << std::endl;
    return 0;
}
A1
B0
C10
DCompilation error
Attempts:
2 left
💡 Hint
The function returns as soon as i equals 1.
Predict Output
advanced
2:00remaining
What error does this code produce?
What error will occur when compiling this code?
C++
#include <iostream>

int f() {
    int x = 5;
    // Missing return statement
}

int main() {
    std::cout << f() << std::endl;
    return 0;
}
ANo error, prints 5
BRuntime error: segmentation fault
CWarning: control reaches end of non-void function
DSyntax error: missing semicolon
Attempts:
2 left
💡 Hint
Functions with non-void return type must return a value.
🧠 Conceptual
expert
2:00remaining
What is the value of x after this function call?
Given the code below, what is the value of x after modify(x) is called?
C++
void modify(int &a) {
    a = 10;
    return;
}

int main() {
    int x = 5;
    modify(x);
    return x;
}
A5
B10
CCompilation error
DUndefined behavior
Attempts:
2 left
💡 Hint
The function modifies the argument by reference.