-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,015
  • 11
  • 37
  • 46

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,595
  • 1
  • 17
  • 35
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
  • 43,525
  • 5
  • 33
  • 63