How to reverse array input

Viewed 67

I'm having trouble doing my code since I'm learning from scratch I don't have any idea how I'm going to print out a reversed input from my array. This is what I have so far:

import java.util.Scanner;
public class ReverseList {
    
public static void main(String[] args) {

    Scanner scan = new Scanner(System.in);

    int[] array = new int[10];
    int num = 0;
    int count = 0;
    int total = 1;
    
        loop: 
        for (count = 0; count <= 10; count++) {
            System.out.print("Enter a number (999 to quit): ");
            num = scan.nextInt();
            
            
            if (num == 999) {
                break loop;

            }
              if (count == 9) {
                break loop;

            }
            
            array[count] = num;
            total = count+1;
        }
    System.out.print("\n The list reversed is:" );

//List Reversed

}
}

And the application output should look similar to:

Enter a number (999 to quit): 19 <enter>
Enter a number (999 to quit): 44 <enter>
Enter a number (999 to quit): 25 <enter>
Enter a number (999 to quit): 16 <enter>
Enter a number (999 to quit): 999 <enter>
The list reversed is:  16 25 44 19
3 Answers

Your current code has a few bugs. First, total should be incremented by one (not count). You should not embed a test on count in the loop. You should not rely on so many different magic numbers. Finally, to print the array contents reversed start with the total number of elements and count backwards. Like,

Scanner scan = new Scanner(System.in);

int[] array = new int[10];
int total = 0;

for (int count = 0; count < array.length; count++) {
    System.out.print("Enter a number (999 to quit): ");
    int num = scan.nextInt();

    if (num == 999) {
        break;
    }
    array[count] = num;
    total++;
}
System.out.println("The list reversed is:");
for (int count = total - 1; count >= 0; count--) {
    System.out.println(array[count]);
}

Do some loop but reversed with i--.

Little explanation:

int i value will be 9, i >= 0 doing this loop to array index 0, i-- will decrease the value each time iteration executed.

for (int i = array.length-1; i >= 0; i--){
    System.out.print(array[i]+" ");
}

Along with the other answers regarding a naïve method of reversing an array, I can suggest the following method to reverse an array:

Using Swapping Technique

In this method, we swap the first element of array with the last element of the array, the second first with the second last, the third first with the third last and so on. This will be repeated until all the elements are swapped. The original array gets replaced by the reversed array.

Implementation of the reverse function is given below:

static void reverse(int array[], int sizeOfArray) {
    int i, k, t;

    for (i = 0; i < sizeOfArray / 2; i++) {
        t = array[i];
        array[i] = array[n - i - 1];
        array[n - i - 1] = t;
    }
Related