Home > Enterprise >  How do I use 'for' to add up the numbers 1-20 in Java?
How do I use 'for' to add up the numbers 1-20 in Java?

Time:06-07

I need to add the numbers 1-20 (1 2 3 4... 20 = 210) only using a for loop, but my output 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);
    }
  }
}

CodePudding user response:

You're not actually adding the numbers, instead just printing them. Here's the solution where you can add them into a separate variable and print the output(i.e. sum) later.

int sum=0;
for(int i=1; i<=20; i  ){
    sum =i;
}
System.out.println(sum);

CodePudding user response:

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);
}
  • Related