Im working on a program that requires you to create an array with 10 elements, and asks the user to enter values for each array. Then, you need to copy the contents of the first array into another array, in reverse order. Can someone walk me through this one?

Im good up to the point where I have to copy the contents into the second array, but Im not too sure how to get the values in the second array in reverse order.

Recommended Answers

All 9 Replies

Well, use a loop from i=1 to 10 and

- get value i from array 1
- store it in place (10-i) in array 2

Dorien
SNIP

thats the logic Im using, but when I print out the contents of the second array, all of the elements are zero.

Well, it's kind of hard to help you when we can't see your code.

Here is the code Im using:

import  java.util.Scanner;

public class Arrays
{
      public static void main (String[ ] args)
      {
             int[] array = new int[10];
             int[] arrayCopy = new int[10];
             int value;
            
            Scanner keyboard = new Scanner(System.in);

            for (int index = 0; index < array.length; index++)
            {
               System.out.print("Enter a value for Element " + (index + 1)  + ": ");
               value = keyboard.nextInt();
               array[index] = value;
            }

            for (index = 10; index > array.length; index--)
                arrayCopy[index] = array[index];
     }
}

Can you copy the code you are using? Sounds like the elements are not being stored.

That's because this for loop is never executed:

for (index = 10; index > array.length; index--)
                arrayCopy[index] = array[index];

'index' has value 10, array.length has value 10.
you say: index > array.length; which translates: 10 > 10 . It will return false and you will not go inside the loop.

Since you set index to be 10 (It is WRONG. Should be 9 ) and then you decrease it, the boolean expression shouldn't use the 'array.length'
You already start from 9 and then go down, so you don't need to check the upper limit.
You need to stop when the index reaches 0: index >= 0; Also if one array used index: arrayCopy[index] the other should use something else because with the way you have them the same elements will go at the same place: arrayCopy[index] = array[index]; .
Doesn't matter that you start from 9 and go to 0

Despite what what you think, your code is NOT implementing dorien's algorithm. Check your second loop again.

(My previous post was concurrent with javaAddict's. I was referring to the OP's code, not javaAddict's)

Thanks James. The light bulb turned on when I saw what JavaAddict had to say.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.