I have a problem in Java:
Given a string, return a string made of the chars at indexes 0,1,4,5,8,9...
I know how to solve it, however I was wondering if it's possible for me to use if-else
in for-loop increment itself, for example:
for (int i=0; i < str.length(); if (i%4==0) i++, else i+=3){
result += str.charAt(i);
}
Can we do something like that?
A for loop doesn't increment anything. Your code used in the for statement does. It's entirely up to you how/if/where/when you want to modify i or any other variable for that matter.
Both increment the number, but ++i increments the number before the current expression is evaluted, whereas i++ increments the number after the expression is evaluated. To answer the actual question, however, they're essentially identical within the context of typical for loop usage.
And in the increment section ( i++ ) we increase the value of our counter value every time we complete a loop of the FOR loop.
We need to use i+=2 in case we need to increment for loop by 2 in java. Let's say we want print all even numbers between 1 to 20 in Java. We can write a for loop and start the loop from 2 by using i=2 in initialization part and increment the loop by 2 in each iteration by using i+=2 .
You can't use an if there but you can use a ternary operator
for (int i = 0; i < str.length(); i += i%4 == 0 ? 1 : 3) {
result += str.charAt(i);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With