confusion on arithmetic of Array Indices

Revision en3, by jaswanthi, 2016-03-05 09:45:13

I am confused when dealing with arithmetic around array indices, majorly around the corner cases.

For ex:

  • Finding word in text ( search of needle in haystack). In following, it should be i <= hayStackTill instead of <
    public int search(char[] haystack, char[] needle) {
            int hayStackTill = haystack.length - needle.length;
            for(int i = 0; i < hayStackTill; i++) // it should be i <= hayStackTill instead of <
    }
  • Given the size of array and count from last, Find the index from start
   int index = a.length - countFromLast; // it should be instead a.length - countFromLast + 1
  • Also, here https://youtu.be/KMBe8Lhhti8?t=12319 Mimino suggests to use +7 , because there is chance of index out of bounds. which is needed only if you don't estimate array indices properly.

Can anyone help with some practice problems around this ( Also any suggestions are welcome).

Tags array, indices, index, arithmetic

History

 
 
 
 
Revisions
 
 
  Rev. Lang. By When Δ Comment
en3 English jaswanthi 2016-03-05 09:45:13 197
en2 English jaswanthi 2016-03-05 08:02:57 35 Tiny change: 'should be i 'should be _i
en1 English jaswanthi 2016-03-05 07:52:56 762 Initial revision (published)