0

I need help on how to calculate sum of the numbers that while loop prints. I have to get numbers 1 to 100 using while loop and calculate all those together. Like 1+2+3...+98+99+100. I can get numbers but can't calculate them together. Here's my code:

public class Loops {
    public static void main(String[] args) throws Exception {
        int i = 1;
        while (i < 101) {
           System.out.print(i);
           i = i + 1;
        }
    }
}

How do I make it only print the last sum? If I try to trick the equation it just hangs.

1
  • Are you asking how to declare another variable and add values of i to it? Commented Nov 18, 2013 at 9:07

5 Answers 5

3

First either change your sum variable or index variable

public class Loops {
 public static void main(String[] args) {
  int sum = 0;
  int i = 1;
  while (i < 101) {
   sum = sum + i;
   ++i;
  }
  System.out.println(sum);
}
Sign up to request clarification or add additional context in comments.

1 Comment

Nice calculate index++ and then just add sum and print it
2

Use another variable instead of i which is the loop variable:

int i   = 1;
int sum = 0;
while (i < 101) {
  sum += i;
  i++;
}

Now sum will contain the desired output. In the previous version, you didn't really loop on all values of i from 1 to 101.

Comments

1

Your sum (i) is also your index. So each time you add to it, you're skipping numbers which you want to add to it.

public class Loops {
 public static void main(String[] args) {
  int sum = 0;
  int i = 1;
  while (i < 101) {
   //System.out.print(i);
   sum = sum + i;
   ++i;
  }
  System.out.println(sum);
}

Alternatively, use the Gauss sum: n(n+1)/2

So, the end sum is 100(101)/2 = 5050

Comments

1

Try the following. Moved the values around a bit to ensure that you add up to 100 and always show the sum.

public static void main(String[] args) throws Exception {

    int i = 1;
    long tot = 1;

    while (i < 100) {   
       i += 1;
       tot += i;
       System.out.print("Number :" + i + "  ,sum="+tot);
    }

}

Comments

-3
public class Loops {
  public static void main(String[] args) throws Exception {
    int i = 1;
    int sum = 0;
    while (i < 101) {
       sum = i + 1;
    }
    System.out.print(sum);
  }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.