Reputation: 1
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 + ".");
}
}
Upvotes: 0
Views: 110
Reputation: 46841
Replace
for(int i=1; i<=myNumber; i=i++)
with
for (int i = 1; i <= myNumber;i++)
to stop infinite loop.
Upvotes: 1
Reputation: 2124
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;
Upvotes: 4