Yahoo Answers is shutting down on May 4th, 2021 (Eastern Time) and beginning April 20th, 2021 (Eastern Time) the Yahoo Answers website will be in read-only mode. There will be no changes to other Yahoo properties or services, or your Yahoo account. You can find more information about the Yahoo Answers shutdown and how to download your data on this help page.
Trending News
Array Question (using Java)?
In the following code fragment, a is an array of ints with at least one element. Write code that modifies a by switching its first and last elements. For example, when a is the array with elements 2, 4, 6, 8 (in that order), then after executing your code a should be the array with elements 8, 4, 6, 2 (in that order).
I will test { 1, 2, 3, 2, 1 }
int[] a = {1, 2, 3, 2, 1 };
To do this, I need to figure out what to call the last element. Since this code must apply to any array of any length, so I cannot simply take out the individual elements of the array by using a specific "a[4]" or something like that.
I can use "a[0]' since it applies to all arrrays--the frist element of all arrays. Can you please help me figure out how to set up this code?
~much appreciated
2 Answers
- AnalProgrammerLv 71 decade agoFavorite Answer
Think of an array of 3 elements. Better still draw an array of 3 elements.
That is elements 0, 1, 2. The first element will always be 0. The last element is your target.
But you have a variable you can use to help.
myArray.length
In the example above the length will be 3. How does that help you? Well the last element is always (length - 1).
Have fun.
- 1 decade ago
Hi! :)
First you'll need to set up a loop that handles the switching.
and Java has a .length you could use to know the total size of the indicated array.
in example:
a.length would be = 5.
So use all this hints in constructing your program.
Good luck!