# Basic array list

Printable View

• January 24th, 2011, 09:08 AM
Trunk Monkeey
Basic array list
I am trying practise questions on arrays but I am stuck on a question.
It says to make a code which will return true if the first or last number is a 6.

So far I have:
Code Java:

```public boolean firstLast6(int[] nums) { int length = nums.length; if(nums[0] == 6){ return true; } if(nums[length] == 6){ return true; } else{ return false; } }```

I am not sure how to get it to check the last number
• January 24th, 2011, 09:13 AM
KevinWorkman
Re: Basic array list
Hint: If an array's length is 6, what is its last index?
• January 24th, 2011, 09:29 AM
Trunk Monkeey
Re: Basic array list
Ah yeah I forgot that everything is one less in an array

thanks
• January 24th, 2011, 09:48 AM
KevinWorkman
Re: Basic array list
It's not that everything is one less, and it's not just with arrays. For example, Strings of length 5 contain 5 characters, but the last character is at position 4.

Or think about this: we're in the 21st century, so why does the year start with 20- and not 21-? Because the first century was actually the "zeroth" hundred years: Years 1-99 were the first century, so years 100-199 were the second century, etc. People actually debate when these centuries technically begin and end because we didn't have a "zeroth" year: did the 21st century begin in the year 2000 or the year 2001?

Or on your 25th birthday, how many birthdays have you actually had? The answer is 26! People don't tend to think about their actual birth day as a birthday, but it would be your zeroth birthday. I'm not sure if that's a great metaphor or not.
• January 24th, 2011, 10:25 AM
xwid
Re: Basic array list
Strings of length 5 contain 5 characters, but the last character is at position 4 because String is an array of char so the last character is [4] because 5-1 = 4.
I just wanted to make it clear.
• January 24th, 2011, 10:51 AM
KevinWorkman
Re: Basic array list
Quote:

Originally Posted by xwid
Strings of length 5 contain 5 characters, but the last character is at position 4 because String is an array of char so the last character is [4] because 5-1 = 4.
I just wanted to make it clear.

Sorry, but I don't think that makes it clear. Where does it say that a String is an array of chars? A String is a string of chars, but where does it define the implementation of String to be that of an array?

The last character is not at index four because five minus one is four. It's there because the first character is at index zero, so the second character is at index one, so the third character is at index two, so the fourth character is at index three, so the fifth character is at index four.

My point is that the "0 index" idea is not specific to arrays. See also: Zero-based numbering - Wikipedia, the free encyclopedia