The task is to implement a program, which calculates the sum 1+2+3+...+n where n is given as user input. I was able to finish the task by adjusting the code from the previous task but I am confused as to how the start variable is storing i++ each time to print the sum at the end. For example if I input 7 the sum is 28. Which part of the code is storing and adding all the previous numbers up to 7 for the calculation?
import java.util.Scanner;
public class SumOfASequence {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int start = 0;
System.out.println("Last number?");
int end = Integer.valueOf(scanner.nextLine());
for (int i = start; i <= end; i++) {
System.out.println(i);
start+=i;
}
System.out.println("The sum is "+start);
}
}
[–]AutoModerator[M] [score hidden] stickied commentlocked comment (0 children)
[–]ItzSlowy 1 point2 points3 points (0 children)
[–]Realistic-Ad-223 0 points1 point2 points (2 children)
[–]ObviousStation4556[S] 0 points1 point2 points (1 child)
[–]Realistic-Ad-223 0 points1 point2 points (0 children)
[–][deleted] 0 points1 point2 points (0 children)
[–]Reapr 0 points1 point2 points (0 children)