Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to declare a reference to an integer variable.
C++
int x = 10; int& [1] = x;
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using a pointer syntax instead of a reference.
Forgetting the ampersand (&) in the declaration.
✗ Incorrect
The code declares r as a reference to the integer variable x.
2fill in blank
mediumComplete the code to modify the original variable through its reference.
C++
int a = 5; int& ref = a; ref [1] 10; // Now a should be 10
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using an arithmetic operator instead of assignment.
Not understanding that the reference acts like the original variable.
✗ Incorrect
Assigning 10 to ref changes the original variable a to 10.
3fill in blank
hardFix the error in the function parameter to accept a reference.
C++
void increment([1] num) { num++; } int main() { int x = 3; increment(x); // x should become 4 }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Passing by value, which does not modify the original variable.
Using a pointer without dereferencing inside the function.
✗ Incorrect
Using int& allows the function to modify the original variable x.
4fill in blank
hardFill both blanks to create a function that swaps two integers using references.
C++
void swap([1]& x, [2]& y) { int temp = x; x = y; y = temp; }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using
void& or const int& which prevents modification.Using pointers instead of references.
✗ Incorrect
The function parameters must be references to int to swap the original values.
5fill in blank
hardFill all three blanks to create a function that returns a reference to the larger of two integers.
C++
int& max([1]& a, [2]& b) { return (a [3] b) ? a : b; }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using
const int& which prevents returning a modifiable reference.Using the wrong comparison operator.
✗ Incorrect
The function returns a reference to the larger integer by comparing a and b.