Reputation: 513
this is my task:
"Write program LoopForNumberSum.java. Display only every second number, starting from 2, to the screen and sum in parenthesis between the last round and current round so far. The looping range is defined in separate variables. Use FOR-loop to solve the problem."
This is the code I have so far:
public class LoopForNumberSum {
public static void main(String args[]) {
int min = 2;
int max = 10;
for(int i = min; i <= max; i+=2) {
int j = i+i;
System.out.println(i + "(" + j + "), ");
}
}
}
^This code prints:
2(4),
4(8),
6(12),
8(16),
10(20),
But I need the number in the parenthesis to start from 2 and the rest would need to be 6, 10, 14 and 18. Like this: "2(2), 4(6)..."
Upvotes: 0
Views: 169
Reputation: 53839
Try:
int sum = 0;
for(int i = 2 ; i <= 10 ; i += 2) {
sum += i;
System.out.println(i + "(" + sum + "), ");
}
Upvotes: 1