I'm currently doing a practice test for a midterm and cannot figure out why line e outputs to 4. Could someone please explain? Thanks.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
#include <iostream>
usingnamespace std;
double down(int x[], int cap, int &gap) {
double ans = 0.0;
for (int i = 0; i < cap; i+= gap)
ans += x[i];
gap += 2;
return ans / 10;
}
int main() {
int x[4] = {9, 1, 3, 2};
int a = 4, b = 2;
cout << x[9/3] << endl; // line (a)
cout << down(x, a, b) << endl; // line (b)
cout << down(x, a, b) << endl; // line (c)
cout << down(x, x[2], x[x[2]]) << endl; // line (d)
cout << x[3] << endl; // line (e)
}
It changes to 4 because in line 16, you pass in x[3] as gap. gap changes its value by 2 inside the down function. Since the array element is passed in by reference, it changes it in the array. Making it 4.
1 2 3 4
cout << down(x, x[2], x[x[2]]) << endl; // x[x[2]] is essentially x[3]. passed by reference.
gap += 2; // since gap is x[3] and is passed by reference, when you add 2 to it.
// It changes the value to 4.