Arrays messed up C++ -
const int n = 5; int person[] = {2, 3, 12, 5, 19}; int big = 0; int small = 100; int i; (i = 0; <= n; i++) { cout << "person[" << << "] ate: " << person[i] << endl; //cin >> person[i]; (int j = i+1; j <= n; j++) { if (person[i] < person[j]) { int tmp = person[i]; person[i] = person[j]; person[j] = tmp; } } if (person[i]>big) big=person[i]; if (person[i]<small) small=person[i]; } cout << "person[" << << "] ate pancakes: " << big << endl; cout << "person[" << << "] ate least pancakes: " << small << endl; cout << "sorted:" << endl; (i = 0; < n; i++) { cout << "person[" << << "]: " << person[i] << endl; } system("pause");
where messed arrays keeps showing me 2 bubble sorting works. , other question how array index smallest value , array index highest value?
in c++ arrays zero 0
indexed. should change loops this:
for (i = 0; < n; i++) ^^^ { // code... (int j = i+1; j < n; j++) ^^^ { // code...
because:
index -> 0 1 2 3 4 person[] = {2, 3, 12, 5, 19};
in code value of i
, j
increment n
5
. means trying access array named person
's 5th index create array index out of bound error.
Comments
Post a Comment