cppintermediate10 minutes

Predict the Output of a Custom Array Transformation Function in C++

Analyze the given C++ code that transforms an integer array through nested loops and conditional swaps. Predict what the output will be when the code is executed with a specific input array.

Challenge prompt

Given the following C++ program, which takes an integer array and modifies it using nested loops and conditional swapping, what will be the final contents of the array after the function processArray is called? Provide the exact output as printed by the main function.

Guidance

  • Trace the nested loops carefully, paying attention to how elements are compared and swapped.
  • Visualize or write down array states after each outer loop iteration to follow changes step-by-step.

Hints

  • Remember that the inner loop starts from the element after the outer loop index, so it compares pairs only forward in the array.
  • Focus on how the conditional swap is triggered only when the current outer element is greater than an inner element.

Starter code

#include <iostream>
#include <vector>
using namespace std;

void processArray(vector<int>& arr) {
    for (int i = 0; i < arr.size(); i++) {
        for (int j = i + 1; j < arr.size(); j++) {
            if (arr[i] > arr[j]) {
                int temp = arr[i];
                arr[i] = arr[j];
                arr[j] = temp;
            }
        }
    }
}

int main() {
    vector<int> data = {8, 3, 7, 1, 9};
    processArray(data);
    for (int num : data) {
        cout << num << " ";
    }
    cout << endl;
    return 0;
}

Expected output

1 3 7 8 9

Core concepts

nested loopsarray manipulationsorting logic

Challenge a Friend

Send this duel to someone else and see if they can solve it.