james
james

Reputation: 55

Sequence For Loop

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

Answers (4)

Tong Liu
Tong Liu

Reputation: 46

for (int counter = 1; counter <=n; counter++){
    System.out.println(a+4*(counter-1));
}

Upvotes: 0

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

Andy Turner
Andy Turner

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

giorashc
giorashc

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

Related Questions