简体   繁体   中英

How do i change the if statement to iterate backwards through the array?

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]); 
    }
}

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

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]); 
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM