Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 2 of 2

Thread: array

  1. #1
    New to the CF scene
    Join Date
    Sep 2011
    Posts
    3
    Thanks
    2
    Thanked 0 Times in 0 Posts

    array

    Hi, I have no errors on this but I want to be sure that the question has been answer corretly. Write an application that can hold 5 integers in an array. first to last then display last to fist.

    [code]
    * To change this template, choose Tools | Templates
    * and open the template in the editor.
    */
    package week

    /**
    *
    * @author Ronnie
    */
    class IntArray1 {
    public static void main(String[] args) {
    int[] anArray; // declares an array of integers

    anArray = new int[5]; // allocates memory for 5 integers

    anArray[0] = 10; // initialize first element
    anArray[1] = 20; // initialize second element
    anArray[2] = 30; // etc.
    anArray[3] = 40;
    anArray[4] = 50;
    anArray[4] = 60; // intialize next group of elements in reverse
    anArray[3] = 70;
    anArray[2] = 80;
    anArray[1] = 90;
    anArray[0] = 100;


    System.out.println("Element at index 0: " + anArray[0]);
    System.out.println("Element at index 1: " + anArray[1]);
    System.out.println("Element at index 2: " + anArray[2]);
    System.out.println("Element at index 3: " + anArray[3]);
    System.out.println("Element at index 4: " + anArray[4]);
    System.out.println("Element at index 4: " + anArray[4]);
    System.out.println("Element at index 3: " + anArray[3]);
    System.out.println("Element at index 2: " + anArray[2]);
    System.out.println("Element at index 1: " + anArray[1]);
    System.out.println("Element at index 0: " + anArray[0]);
    }
    }
    [code]
    thanks

  • #2
    God Emperor Fou-Lu's Avatar
    Join Date
    Sep 2002
    Location
    Saskatoon, Saskatchewan
    Posts
    16,994
    Thanks
    4
    Thanked 2,662 Times in 2,631 Posts
    This isn't correct. You are overwritting the array by counting up to 4, then reversing. The ending array will be {100, 90, 80, 70, 60}, which I don't think you want.
    Its a simple matter of just writing the 0 through 4, not back down from 4 to 0. Then when you print it, you simply print anArray[4] down through 0, or if you've covered loops:
    PHP Code:
    for (int i anArray.length 1>= 0; --i)
    {
        
    System.out.println("Element at " " is " anArray[i]);


  • Users who have thanked Fou-Lu for this post:

    hillary (09-22-2011)


  •  

    Tags for this Thread

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •