Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

This is my array code and I need to print it in reverse.

public class Array1D {
    public static void main(String[] args) {
        int[] array = new int[3];
        array[0] = 1;
        array[1] = 2;
        array[2] = 5;
        for (int i = 0; i < array.length; i++) { //loop
            System.out.print("array["+i+"]=");
            System.out.println(array[i] + "   ");
        }
        System.out.println("the last element in the matrix = " + array[array.length - 1]); // finding the last element in the array
        System.out.println("   ");
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
150 views
Welcome To Ask or Share your Answers For Others

1 Answer

Just reverse the direction of your for loop. Right now it is counting from 0 to the length, have it count from the length to zero

for (int i = array.length-1; i >= 0; i--)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...