Efficient methods for Incrementing and Decrementing in the same Loop

Anthony Neace picture Anthony Neace · Oct 17, 2012 · Viewed 34.8k times · Source

Suppose some situations exist where you would like to increment and decrement values in the same for loop. In this set of situations, there are some cases where you can "cheat" this by taking advantage of the nature of the situation -- for example, reversing a string.

Because of the nature of building strings, we don't really have to manipulate the iterate or add an additional counter:

public static void stringReversal(){
    String str = "Banana";
    String forwardStr = new String();
    String backwardStr = new String();

    for(int i = str.length()-1; i >= 0; i--){
        forwardStr = str.charAt(i)+forwardStr;
        backwardStr = backwardStr+str.charAt(i);
    }

    System.out.println("Forward String:  "+forwardStr);
    System.out.println("Backward String: "+backwardStr);   
}

However, suppose a different case exists where we just want to print a decremented value, from the initial value to 0, and an incremented value, from 0 to the initial value.

public static void incrementAndDecrement(){

   int counter = 0;

   for(int i = 10; i >= 0; i--){
       System.out.println(i);
       System.out.println(counter);
       counter++;
   } 
}

This works well enough, but having to create a second counter to increment seems messy. Are there any mathematical tricks or tricks involving the for loop that could be used that would make counter redundant?

Answer

Jon Skeet picture Jon Skeet · Oct 17, 2012

Well it looks like you just want:

for(int i = 10; i >= 0; i--){
    System.out.println(i);
    System.out.println(10 - i);
} 

Is that the case? Personally I'd normally write this as an increasing loop, as I find it easier to think about that:

for (int i = 0; i <= 10; i++) {
    System.out.println(10 - i);
    System.out.println(i);
} 

Note that your string example is really inefficient, by the way - far more so than introducing an extra variable. Given that you know the lengths involved to start with, you can just start with two char[] of the right size, and populate the right index each time. Then create a string from each afterwards. Again, I'd do this with an increasing loop:

char[] forwardChars = new char[str.length()];
char[] reverseChars = new char[str.length()];
for (int i = 0; i < str.length(); i++) {
    forwardChars[i] = str.charAt(i);
    reverseChars[reverseChars.length - i - 1] = str.charAt(i);
}
String forwardString = new String(forwardChars);
String reverseString = new String(reverseChars);

(Of course forwardString will just be equal to str in this case anyway...)