I need to add the numbers 1-20 (1 + 2 + 3 + 4…+ 20 = 210) only using a for loop, but my out put keeps coming out as 1234567891011121314151617181920. Where am I going wrong?
public class Objective8Lab2 {
public static void main(String[] args) {
int sum = 0;
for (int i=1; i<=20 - sum; i++){
System.out.print(i);
}
}
}
>Solution :
What are you missing out here is adding the variable i to sum. Instead you are printing the value of i – hence you are seeing 1,2,3… being printed one after the other.
The code below should give a fair idea of what needs to change.
public class Objective8Lab2 {
public static void main(String[] args) {
int sum = 0;
for (int i=1; i<=20; i++){
sum = sum + i;
}
System.out.print(sum);
}