0

I wrote the following code to accept an integer from the user through console input. The code is supposed to add the positive integers from one to the number chosen by the user to yield a sum. For example, if the user enters 5, the output should be 15 (1+2+3+4+5). For some reason, this code I wrote ends up outputting the square of whatever value the user inputs. That is, a user input of 4 results in 16, etc. This is clearly wrong. If you have any insights that might help me fix this, I would certainly appreciate it. Many thanks!

import java.util.Scanner;

public class OneDashSix{
    public static void main(String[] args){
        //Create a new scanner object
        Scanner input=new Scanner(System.in);
        //Receive user input

        System.out.print("Enter an integer for which you would like to find the arithmetic sum: ");
        int myNumber=input.nextInt();
        int sum = 0;
        //Calculate the sum of the arithmetic series
        for(int i=1; i<=myNumber; i=i++)
        {
            sum=sum+myNumber;
        }
        //Display the results to the console
        System.out.println("The sum of the first " + 
        myNumber + " positive integers is " + sum + ".");
    }
}
2
  • Thats because you're just adding "myNumber" "myNumber" times. Commented Apr 6, 2014 at 13:59
  • yes try adding the loop index i Commented Apr 6, 2014 at 14:10

2 Answers 2

4

This line

sum=sum+myNumber;

needs to be

sum=sum+i;

EDIT: For what it's worth...the fastest way to do it would actually be to discard the loop:

sum = (myNumber * (myNumber + 1)) / 2;
Sign up to request clarification or add additional context in comments.

3 Comments

Good one (n * (n+1))/2 formula.
@Braj thanks, even though I'm guessing it probably defeats the purpose of the assignment. :P
you can suggest better ways all the time. :)
1

Replace

for(int i=1; i<=myNumber; i=i++)

with

for (int i = 1; i <= myNumber;i++) 

to stop infinite loop.

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.