3 Replies - 1475 Views - Last Post: 03 February 2011 - 04:36 PM Rate Topic: -----

#1 newjava  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 23
  • Joined: 27-January 11

Displaying and Reversing Array

Posted 03 February 2011 - 04:25 PM

I am trying to display an array from first to last and then from last to first. I have this code, which does work correctly, but I am sure there is a more efficient way to display the array from last to first. Any help is appreciated.
public class IntArray
{
  public static void main(String[] args)
  {
    int[] numbers = {3, 5, 9, 10, 11};
    int x;
    for(x = 0; x < numbers.length; ++x)
      System.out.print(numbers[x]);
    System.out.print(" " + numbers[4]);
    System.out.print(numbers[3]);
    System.out.print(numbers[2]);
    System.out.print(numbers[1]);
    System.out.print(numbers[0]);
  }
}


Is This A Good Question/Topic? 0
  • +

Replies To: Displaying and Reversing Array

#2 Dogstopper  Icon User is offline

  • The Ninjaducky
  • member icon



Reputation: 2870
  • View blog
  • Posts: 11,025
  • Joined: 15-July 08

Re: Displaying and Reversing Array

Posted 03 February 2011 - 04:28 PM

You have this for loop:
for(x = 0; x < numbers.length; ++x)



Instead of moving from 0 to numbers.length -1, move from index.length-1 to 0. Like this:
for(x = numbers.length-1; x >= 0; --x)


Was This Post Helpful? 1
  • +
  • -

#3 japanir  Icon User is offline

  • jaVanir
  • member icon

Reputation: 1010
  • View blog
  • Posts: 3,025
  • Joined: 20-August 09

Re: Displaying and Reversing Array

Posted 03 February 2011 - 04:31 PM

What would you do if the array had 1000 elements? printing each element would be a pain...
As you looped the array using x as the index (getting values from 0 to numbers.length - 1) and increasing it to print the array in its order, use another loop to print the array backwards, but this time decrease x, assigning it values from numbers.length - 1 to 0.
for(x = numbers.length - 1; x  >= 0; x--)
      System.out.print(numbers[x]);


Ninjad by the Ninjaducky :)

This post has been edited by japanir: 03 February 2011 - 04:33 PM

Was This Post Helpful? 2
  • +
  • -

#4 newjava  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 23
  • Joined: 27-January 11

Re: Displaying and Reversing Array

Posted 03 February 2011 - 04:36 PM

Ok, thanks. I could not figure out how to write the loop for the reverse. I got it now.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1