Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do i use 'for' to add up the numbers 1-20 in Java?

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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);
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading