settingsAccountsettings
Menusettings

Q: Sum numbers from 1 to N - Java Task

+7 votes

Create a Java program that reads a number N from the console and calculates the sum of all numbers from 1 to N (inclusive).

Must be like this:

Sum numbers from 1 to N - Java

asked in Java category by user hues
edited by user golearnweb

1 Answer

+1 vote
 
Best answer

This inclusive means that in the for loop you must be careful - add <=; Here is my solution:

import java.util.Scanner;

public class SumNumbersFromOneToN06 {
    public static void main(String[] args) {
        Scanner console = new Scanner(System.in);

        int number = Integer.parseInt(console.nextLine());

        int sum = 0;
        for (int i = 0; i <= number; i++) {
            sum = sum + i;
        }
        System.out.println(sum);
    }
}
answered by user john7
selected by user golearnweb
...