Consider the following C code snippet. What will be printed when printf("%d", add(3, 4)); is executed?
int add(int a, int b) { return a + b; } int main() { printf("%d", add(3, 4)); return 0; }
Remember that the return statement sends back the sum of the two numbers.
The function add returns the sum of a and b. So, add(3, 4) returns 7, which is printed.
What is the return value of the function mystery when called with mystery(5)?
int mystery(int x) { if (x > 0) { return x * 2; } else { return -1; } }
Check the condition and what happens when x is positive.
Since 5 is greater than 0, the function returns 5 * 2 = 10.
What will be printed when printf("%d", factorial(4)); is executed?
int factorial(int n) { if (n == 0) { return 1; } else { return n * factorial(n - 1); } } int main() { printf("%d", factorial(4)); return 0; }
Recall that factorial of 4 is 4 * 3 * 2 * 1.
The function calculates factorial recursively. factorial(4) = 4 * factorial(3) = 24.
What happens when int result = no_return(); is executed given the function below?
int no_return() { int x = 5; x += 3; // Missing return statement } int main() { int result = no_return(); printf("%d", result); return 0; }
Functions declared to return a value must have a return statement.
The function no_return lacks a return statement, which leads to undefined behavior or compiler warnings.
Given the code below, what is the value of x after x = update(10); is executed?
int update(int a) { a = a + 5; return a; } int main() { int x = 0; x = update(10); return 0; }
The function returns the updated value of a.
The function adds 5 to the input and returns it. So x becomes 15.