Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using if else in For Loop increment

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?

like image 441
geerky42 Avatar asked Oct 29 '15 14:10

geerky42


People also ask

Can you increment in a for loop?

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.

Should I use i ++ or ++ i in for loop?

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.

What is i ++ in for loop?

And in the increment section ( i++ ) we increase the value of our counter value every time we complete a loop of the FOR loop.

Can I increment by 2 in a for loop in Java?

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 .


1 Answers

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);
}
like image 106
Manos Nikolaidis Avatar answered Sep 22 '22 12:09

Manos Nikolaidis