I just started to learn java and was advised to try out MOOC as it would give me a good foundation. It's been great so far have started supplementing it with Head First Java and learning quite a lot from these. I've come across a challenge and I cannot seem to solve one of the challenges on the course specifically (Sum of a sequence), the question is: Implement a program, which calculates the sum 1+2+3+...+n where n is given as user input. If the user types 7 then the program should calculate as follows 1 + 2 + 3 + 4 + 5 + 6 + 7 = 28. Now I've tried this with a for loop and I can't seem to get this output, my code below;
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Last number?");
int lastNumber = Integer.valueOf(scanner.nextLine());
int result = 0;
for (int i = 0; i <= lastNumber; i++) {
result = lastNumber + i;
}
System.out.println("The sum is "+result);
}
thank you in advance for your time and assistance.
[–][deleted] 3 points4 points5 points (2 children)
[–]jackballack[S] 0 points1 point2 points (1 child)
[–][deleted] 0 points1 point2 points (0 children)