Effective methods for increasing and decreasing in one cycle

Suppose that there are some situations in which you would like to increase and decrease the values โ€‹โ€‹in the same for the loop. There are cases in this set of situations where you can โ€œcheatโ€ it using the nature of the situation โ€” for example, by reversing the string.

Due to the nature of string strings, we do not need to manipulate iteration or add an extra 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 there is another case where we just want to print a decremented value from the initial value to 0 and an increased value from 0 to the original 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 pretty well, but creating a second counter to increase seems messy. Are there any math tricks or tricks using a for loop that could be used to make counter redundant?

+4
source share
2 answers

Well, it looks like you just want:

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

This is true? Personally, I would usually write this as a growing cycle, as it was easier for me to think about this:

 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 - much more than introducing an extra variable. Given that you know how long to start, you can start with two char[] right size and fill in the right index each time. Then create a line from each afterwards. Again, I would do this with an increase in the 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 in this case will be str anyway ...)

+8
source

In a for loop, you can have several variables and increments.

 for(int i = 10, j = 0; i >= 0; i--, j++) { System.out.println(i); System.out.println(j); } 
+4
source

Source: https://habr.com/ru/post/1440210/


All Articles