[java] How to make for loops in Java increase by increments other than 1

If you have a for loop like this:

for(j = 0; j<=90; j++){}

It works fine. But when you have a for loop like this:

for(j = 0; j<=90; j+3){}

it doesn't work. Could someone please explain this to me?

This question is related to java loops for-loop

The answer is


Simply try this

for(int i=0; i<5; i=i+2){//value increased by 2
//body
}

OR

for(int i=0; i<5; i+=2){//value increased by 2
//body
}

Since nobody else has actually tackled Could someone please explain this to me? I believe I will:

j++ is shorthand, it's not an actual operation (ok it really IS, but bear with me for the explanation)

j++ is really equal to the operation j = j + 1; except it's not a macro or something that does inline replacement. There are a lot of discussions on here about the operations of i+++++i and what that means (because it could be intepreted as i++ + ++i OR (i++)++ + i

Which brings us to: i++ versus ++i. They are called the post-increment and pre-increment operators. Can you guess why they are so named? The important part is how they're used in assignments. For instance, you could do: j=i++; or j=++i; We shall now do an example experiment:

// declare them all with the same value, for clarity and debug flow purposes ;)
int i = 0;
int j = 0;
int k = 0;

// yes we could have already set the value to 5 before, but I chose not to.
i = 5;

j = i++;
k = ++i;

print(i, j, k); 
//pretend this command prints them out nicely 
//to the console screen or something, it's an example

What are the values of i, j, and k?

I'll give you the answers and let you work it out ;)

i = 7, j = 5, k = 7; That's the power of the pre and post increment operators, and the hazards of using them wrong. But here's the alternate way of writing that same order of operations:

// declare them all with the same value, for clarity and debug flow purposes ;)
int i = 0;
int j = 0;
int k = 0;

// yes we could have already set the value to 5 before, but I chose not to.
i = 5;

j = i;
i = i + 1; //post-increment

i = i + 1; //pre-increment
k = i;

print(i, j, k); 
//pretend this command prints them out nicely 
//to the console screen or something, it's an example

Ok, now that I've shown you how the ++ operator works, let's examine why it doesn't work for j+3 ... Remember how I called it a "shorthand" earlier? That's just it, see the second example, because that's effectively what the compiler does before using the command (it's more complicated than that, but that's not for first explanations). So you'll see that the "expanded shorthand" has i = AND i + 1 which is all that your request has.

This goes back to math. A function is defined where f(x) = mx + b or an equation y = mx + b so what do we call mx + b ... it's certainly not a function or equation. At most it is an expression. Which is all j+3 is, an expression. An expression without assignment does us no good, but it does take up CPU time (assuming the compiler doesn't optimize it out).


I hope that clarifies things for you and gives you some room to ask new questions. Cheers!


That’s because j+3 doesn’t change the value of j. You need to replace that with j = j + 3 or j += 3 so that the value of j is increased by 3:

for (j = 0; j <= 90; j += 3) { }

for(j = 0; j<=90; j = j+3)
{

}

j+3 will not assign the new value to j, add j=j+3 will assign the new value to j and the loop will move up by 3.

j++ is like saying j = j+1, so in that case your assigning the new value to j just like the one above.


If you have a for loop like this:

for(j = 0; j<=90; j++){}

In this loop you are using shorthand provided by java language which means a postfix operator(use-then-change) which is equivalent to j=j+1 , so the changed value is initialized and used for next operation.

for(j = 0; j<=90; j+3){}

In this loop you are just increment your value by 3 but not initializing it back to j variable, so the value of j remains changed.


In your example, j+=3 increments by 3.

(Not much else to say here, if it's syntax related I'd suggest Googling first, but I'm new here so I could be wrong.)


for (let i = 0; i <= value; i+=n) { // increments by n
/*code statement*/
}

this format works for me incrementing index by n

for (let i = 0; i <= value; i+=4) { // increments by 4
/*code statement*/
}

if n = 4 this it will increment by 4


It's just a syntax error. You just have to replace j+3 by j=j+3 or j+=3.


Change

for(j = 0; j<=90; j+3)

to

for(j = 0; j<=90; j=j+3)

The "increment" portion of a loop statement has to change the value of the index variable to have any effect. The longhand form of "++j" is "j = j + 1". So, as other answers have said, the correct form of your increment is "j = j + 3", which doesn't have as terse a shorthand as incrementing by one. "j + 3", as you know by now, doesn't actually change j; it's an expression whose evaluation has no effect.


for(j = 0; j<=90; j++){}

j++ means j=j+1, j value already 0 now we are adding 1 so now the sum value of j+1 became 1, finally we are overriding the j value(0) with the sum value(1) so here we are overriding the j value by j+1. So each iteration j value will be incremented by 1.

for(j = 0; j<=90; j+3){}

Here j+3 means j value already 0 now we are adding 3 so now the sum value of j+3 became 3 but we are not overriding the existing j value. So that JVM asking the programmer, you are calculating the new value but where you are assigning that value to a variable(i.e j). That's why we are getting the compile-time error " invalid AssignmentOperator ".

If we want to increment j value by 3 then we can use any one of the following way.

 for (int j=0; j<=90; j+=3)  --> here each iteration j value will be incremented by 3.
 for (int j=0; j<=90; j=j+3) --> here each iteration j value will be incremented by 3.  

You can also write code as

for(int i=0;i<n;i++)
{
      //statements;
      i=i+2;//cause you want to increment i by 3 
}

It should be like this

for(int j = 0; j<=90; j += 3) 

but watch out for

for(int j = 0; j<=90; j =+ 3) 

or

for(int j = 0; j<=90; j = j + 3)

Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to loops

How to increment a letter N times per iteration and store in an array? Angular 2 Cannot find control with unspecified name attribute on formArrays What is the difference between i = i + 1 and i += 1 in a 'for' loop? Prime numbers between 1 to 100 in C Programming Language Python Loop: List Index Out of Range JavaScript: Difference between .forEach() and .map() Why does using from __future__ import print_function breaks Python2-style print? Creating an array from a text file in Bash Iterate through dictionary values? C# Wait until condition is true

Examples related to for-loop

List append() in for loop Prime numbers between 1 to 100 in C Programming Language Get current index from foreach loop how to loop through each row of dataFrame in pyspark TypeScript for ... of with index / key? Is there a way in Pandas to use previous row value in dataframe.apply when previous value is also calculated in the apply? Python for and if on one line R for loop skip to next iteration ifelse How to append rows in a pandas dataframe in a for loop? What is the difference between ( for... in ) and ( for... of ) statements?