How do i return an array to display from backwards

30 Views Asked by At

hey so am new in java and haven't gotten in my head the logic on how to print an array backwards. I just don't understand how it flows using forloop

its fairly easy and chatgpt could easily do it whats bothering me though is i dont understand it so if it could be provided with proper explanation i would appreciate it

this is an example of what i mean {1,2,3,4,5}

display would be - {5,4,3,2,1}

3

There are 3 best solutions below

1
Malvin Lok On

do you mean:

public class Main {
    public static void main(String[] args) {
        // your array
        int[] arr = {1,2,3,4,5};

        // loop to print the array backwards
        for(int i = arr.length - 1; i >= 0; i--){
            System.out.print(arr[i] + " ");
        }
    }
}
0
Basil Bourque On

You asked:

i dont understand it so if it could be provided with proper explanation

Arrays

As shown in The Java Tutorials by Oracle Corp, a for loop has three parts:

for ( initialization ; termination ; increment ) 
{
    statement(s)
}

Take for example an array { "alpha" , "beta" , "gamma" }:

for ( int index = 0 ; index < myArray.length ; index ++ )
{
    System.out.println( "Index: " + index + ", value: " + myArray[ index ] );
}

See this code run at Ideone.com.

------|  Ascending  |----------
Index: 0, Value: alpha
Index: 1, Value: beta
Index: 2, Value: gamma

To reverse the direction:

  • The first part, initialization, can start at the last index of the array rather than at the first index (zero). Ex: int index = ( myArray.length - 1 ). (Parentheses optional there.)
  • The second part, termination, can test for going past the first index (zero), into negative numbers: index > -1 (or index >= 0).
  • The third part, increment, can go downwards (negative) rather than upwards (positive): index --.
for ( int index = ( myArray.length - 1 ) ; index > -1 ; index -- )
{
    System.out.println( "Index: " + index + ", value: " + myArray[ index ] );
}

See this code run at Ideone.com.

------|  Descending  |----------
Index: 2, value: gamma
Index: 1, value: beta
Index: 0, value: alpha

Collections

The code above certainly works. And, on the upside, arrays tend to use less memory while executing faster. But, on the downside, working with arrays is limiting, cumbersome, and somewhat error-prone.

More commonly in Java, we use the Java Collections Framework.

In collections, the appropriate replacement for an array is a SequencedCollection such as ArrayList (a List) or TreeSet (a NavigableSet).

We can easily make an unmodifiable List of our array by calling List.of. (The concrete actually used under-the-covers is unspecified.) The List.of method performs a shallow copy. This means the content of the elements is not duplicated — the same three String object are in both the original array and in the new List.

Every List is also a SequencedCollection. This means we can call the reversed method. This method is quite efficient in that it does not really create another collection. Instead the reversed method creates a view upon the original collection that presents its elements in a reversed encounter order.

String[] myArray = { "alpha" , "beta" , "gamma" };
SequencedCollection < String > strings = List.of( myArray );

System.out.println( "strings.toString() = " + strings );
System.out.println( "strings.reversed().toString() = " + strings.reversed().toString() );

When run:

strings.toString() = [alpha, beta, gamma]
strings.reversed().toString() = [gamma, beta, alpha]
0
Muhammad Nouman On

    // inizliase the array 
        int[] arr = {1,2,3,4,5};
    // we start from reservse so we write like this 
        for(int i = arr.length - 1; i >= 0; i--){
            System.out.print(arr[i] + " ");
        }

In the following code, we start the value of the array from (length - 1) to 0 line in the code i start from 4 to 0 when we run the loop as in the 4 index we have 5 value so 5 will print after printing the value of i will be minus so it will be 3 now and it array 3 index we have 4 value of an array and it goes the same as i value becomes 0 then loop we terminate.