Java Integer Addition Within a For Loop -
i wrote following code accept integer user through console input. code supposed add positive integers 1 number chosen user yield sum. example, if user enters 5, output should 15 (1+2+3+4+5). reason, code wrote ends outputting square of whatever value user inputs. is, user input of 4 results in 16, etc. wrong. if have insights might me fix this, appreciate it. many thanks!
import java.util.scanner; public class onedashsix{ public static void main(string[] args){ //create new scanner object scanner input=new scanner(system.in); //receive user input system.out.print("enter integer find arithmetic sum: "); int mynumber=input.nextint(); int sum = 0; //calculate sum of arithmetic series for(int i=1; i<=mynumber; i=i++) { sum=sum+mynumber; } //display results console system.out.println("the sum of first " + mynumber + " positive integers " + sum + "."); } }
this line
sum=sum+mynumber;
needs be
sum=sum+i;
edit: it's worth...the fastest way discard loop:
sum = (mynumber * (mynumber + 1)) / 2;
Comments
Post a Comment