Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reverse for-loop - explanation wanted

I've been programing in java for a while now but I'm just getting back to the basics and try to actually understand what is going on.

The syntax for reversing a string using a for-loop that decrements instead of incrementing is

for (int i = string.length() - 1; i >= 0; i--)

But I don't really understand why I have to put " - 1 " after .length()? Here's my code.

public static void main(String[] args) {
    // TODO Auto-generated method stub
    reverseVertical("laptop");
}

private static void reverseVertical(String string) {
    // TODO Auto-generated method stub

    for (int i = string.length() - 1; i >= 0; i--) {
        System.out.println(string.charAt(i));
    }

}

What is the logic behind the " - 1 "? I can't make any sense of it - other than it actually works.

like image 546
Charles Avatar asked Dec 09 '22 02:12

Charles


1 Answers

If a string has 4 characters, you'll get the first one via charAt(0), and the last one via charAt(3), because the index is zero based. So your loop would start at 3 and ends at 0, and not start at 4.

like image 89
JP Moresmau Avatar answered Dec 22 '22 03:12

JP Moresmau