Returning References

Medium References
Solve in Playground →

Problem Statement

Write a C++ program defining a function that returns a reference to a global or static element in an array, allowing caller modification.

Input Format

First line: N. Second line: N integers. Third line: Index I and new value V.

Output Format

Print modified array elements separated by a space.

Constraints

1 <= N <= 100, 0 <= I < N

Sample Input

4
10 20 30 40
2 99

Sample Output

10 20 99 40

Explanation

Functions returning references allow assigning values directly to the returned reference location.

Starter Code

#include <iostream>
#include <vector>

int& getElement(std::vector<int>& arr, int idx) {
    return arr[idx];
}

int main() {
    int n;
    if (std::cin >> n) {
        std::vector<int> arr(n);
        for (int i = 0; i < n; i++) std::cin >> arr[i];
        int idx, val;
        if (std::cin >> idx >> val) {
            getElement(arr, idx) = val;
            for (int i = 0; i < n; i++) {
                std::cout << arr[i];
                if (i < n - 1) std::cout << " ";
            }
            std::cout << "n";
        }
    }
    return 0;
}

Limits

  • Time Limit: 1s
  • Memory Limit: 256MB

Embedded C Programming

Updated: March 15, 2026
Intermediate

Embedded systems rely on efficient low-level programming to interact directly with hardware. In this course, you will learn how to write practical Embedded C programs used in real microcontroller-based systems. Rather than focusing only on theory, this course follows a practice-driven approach. Each lesson includes hands-on coding exercises that simulate real firmware development tasks used