0

I have tried putting i=sum in last for loop but it didn't work. I think it is getting wrong in the last for loop part.

please explain Why I can't write for(i=sum;i<arr1.length;i--)

Can you please suggest how can I achieve the reverse operation?

import java.util.*;

class ReverseArray {
  static Scanner sc = new Scanner(System.in);

  public static void main(String[] args) {
    int j = 0;
    System.out.println("How many numbers u want to enter? ");
    int num = sc.nextInt();
    int arr[] = new int[num];
    int arr1[] = new int[num];

    System.out.println("Please enter the " + num + " numbers");

    for (int i = 0; i < num; i++) {
      arr[i] = sc.nextInt();
      arr1[i] = arr[i];

    }
    System.out.println("The elements that u have entered are: ");
    for (int x : arr) {
      System.out.println(x);
    }
    System.out.println("Numbers in reverse oreder: ");
    for (int i = 3; i <= arr1.length; i--) {
      System.out.println(arr1[i]);
    }
  }
}
Yash Deole
  • 515
  • 4
  • 8
  • 1
    The condition should be `for(int i=arr.length-1; i>=0; i--)` – Gautham M Jun 14 '21 at 10:55
  • Does this answer your question? [How to print the counting in reverse order from 10 to 1 in java?](https://stackoverflow.com/questions/46745726/how-to-print-the-counting-in-reverse-order-from-10-to-1-in-java) Here in the loop, the loop counter is initialized to 10, instead you need to initialize it to `arr1.length` – Gautham M Jun 14 '21 at 10:59
  • Does this answer your question? [How do I reverse an int array in Java?](https://stackoverflow.com/questions/2137755/how-do-i-reverse-an-int-array-in-java) – csalmhof Jun 14 '21 at 10:59
  • 2
    @csalmhof Even though it serves the purpose, that question reverses the contents of the array. The OP is actually looking to just print the elements in reverse order. – Gautham M Jun 14 '21 at 11:04
  • why do you not use inbuilt function? Collections.reverse(Arrays.asList(arr1)); – Pirate Jun 14 '21 at 11:15

1 Answers1

0

for(int i = arr1.length; i >= 3;i--){System.out.println(arr1[i]);

if you get an out of range error try i > 3 instead of >=

user14990172
  • 3
  • 1
  • 3
  • i dont know until wich position it should end in your code you started with 3. But you can replace it with 0 for(int i=arr.length-1; i>=0; i--) – user14990172 Jun 14 '21 at 12:46