programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
• Campbell Ritchie
• Liutauras Vilda
• Tim Cooke
• Jeanne Boyarsky
• Paul Clapham
Sheriffs:
• Devaka Cooray
• Ron McLeod
• paul wheaton
Saloon Keepers:
• Tim Moores
• Piet Souris
• Tim Holloway
• Stephan van Hulst
• Carey Brown
Bartenders:
• Al Hobbs
• Frits Walraven
• Scott Selikoff

Ending Loops with [i+1]

Ranch Hand
Posts: 66
• Number of slices to send:
Optional 'thank-you' note:
Hello friends,

I am back at another project and got stuck at a certain point.

During the task I want to compare two elements of an array a[i] and a[i+1].
My problem is that I always get Out of Bound errors for the last number because I think the program also tries to compare it with a[i+1] which is not in the array for the last number.
How can I solve this issue?

Thank you very much in advance.

Marshal
Posts: 76822
366
• 1
• Number of slices to send:
Optional 'thank-you' note:
Your logic to find whether the array is sorted decreasingly won't work.
If you put number in all the indices, you will find that when you get to the end of your 20‑element array, you will be working with j = 19. If you try to work out whether the next element is less than array[19], you will end up using array[20] which of course doesn't exist. Try...or...If you have a 20‑element array, you will have 19 comparisons. That is a fencepost number.

Sheriff
Posts: 17288
299
• Number of slices to send:
Optional 'thank-you' note:
For your reference, look up fencepost error, also known as off-by-one error

The two hardest things in programming:
1. Choosing good names
2. Cache invalidation
3. Off-by-one errors

 "I know this defies the law of gravity... but I never studied law." -B. Bunny Defiant tiny ad: the value of filler advertising in 2021 https://coderanch.com/t/730886/filler-advertising