• Post Reply Bookmark Topic Watch Topic
  • New Topic
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
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
Mac Android IntelliJ IDE Eclipse IDE Spring Debian Java Ubuntu Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
reply
    Bookmark Topic Watch Topic
  • New Topic