-1

How do I iterate backwards through the array? What do I need to do to the for statement?

public static void main(String args[])
{
    int a[] = {0, 1, 2, 3};
    for (int i=1; i<=a.length; i++)
    {
        System.out.println("a[i] = " + a[i]); 
    }
}
Al Foиce ѫ
  • 4,195
  • 12
  • 39
  • 49

2 Answers2

3

In case it about traversing the array backwards you can do like this

public static void main(String args[])
    {
        int a[] = {0, 1, 2, 3};
        for (int i=a.length -1 ; i>=0; i--)
        {
            System.out.println("a[i] = " + a[i]); 
        }
    }
} 

Output

a[i] = 3
a[i] = 2
a[i] = 1
a[i] = 0
mhasan
  • 3,703
  • 1
  • 18
  • 37
1

Start from the length minus one and go back to zero

for (int i = a.length -1; a >= 0; i--)
{
    System.out.println("a[i] = " + a[i]); 
}
Scary Wombat
  • 44,617
  • 6
  • 35
  • 64