Any idea why my code adds a new number in that I never entered when sorted? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Any idea why my code adds a new number in that I never entered when sorted?

https://code.sololearn.com/csOdD5V207Wc/#cpp

4th Sep 2017, 12:26 AM
Chris
Chris - avatar
4 Answers
+ 12
Remember that when referencing elements in an array you start at 0 for the first element. So if the size of an array is 5 the last element is stored at position 4
4th Sep 2017, 12:45 AM
jay
jay - avatar
+ 5
You're comparing past the end of the array at line 36, then storing the number past the end at 39 and 40; your loop appears too long at 34: 34: for(int j=0; j<size; j++) { 36: if(arr[j]>arr[j+1]) { temp=arr[j]; 39: arr[j]=arr[j+1]; 40: arr[j+1]=temp; This works for me: 34: for(int j=0; j<size-1; j++)
4th Sep 2017, 12:36 AM
Kirk Schafer
Kirk Schafer - avatar
+ 5
If you want to prove to yourself that you're getting the number just past the end of the array, add this in sort just before your loops: cout << arr[5]; The number it prints will be the unexplained inserted number.
4th Sep 2017, 12:42 AM
Kirk Schafer
Kirk Schafer - avatar
+ 1
Thanks
4th Sep 2017, 7:05 PM
Chris
Chris - avatar