Reputation: 55
I'm trying to create a for loop to sequentially add 4 to a random value (r) as many times as the value of (n).
I came up with this:
for (int counter = 1; counter <=n; counter++){
System.out.println(a = a + 4);
}
The thing is if the random value were to be 10 for example, it will start counting from 14, 18, 22.
I want it to start counting at the number itself so the results are 10, 14, 18 not to start +4 from the random number selected.
Upvotes: 3
Views: 2066
Reputation: 46
for (int counter = 1; counter <=n; counter++){
System.out.println(a+4*(counter-1));
}
Upvotes: 0
Reputation: 58848
Print the current number before adding 4 to it, then.
System.out.println(a); // print the number
a = a + 4; // THEN add 4
Upvotes: 2
Reputation: 140319
Change your loop body to:
System.println(a);
a += 4;
Or the whole loop to
for (int counter = 1; counter <=n; counter++, a += 4){
System.out.println(a);
}
Upvotes: 3
Reputation: 13713
Then do not increase a
before printing it.
a = a + 4
will first increment a
by 4 store the result in a
and only then print it.
What you need is :
for (int counter = 1; counter <=n; counter++){
System.out.println(a);
a += 4;
}
Upvotes: 2