sum n numbers in java code example

Example 1: java sum 1 to n

public class Main {
  public static void main(String[] args) {
    var scanner = new java.util.Scanner(System.in);
    System.out.print("What is n? ");
    int n = scanner.nextInt();
    int sum = 0;
    for (int i = 1; i <= n; ++i) {
      sum += i;
    }
    System.out.println("The sum of 1..n is " + sum);
  }
}

Example 2: sum of numbers in java

public class SumNatural {

    public static void main(String[] args) {

        int num = 100, sum = 0;

        for(int i = 1; i <= num; ++i)
        {
            // sum = sum + i;
            sum += i;
        }

        System.out.println("Sum = " + sum);
    }
}

Tags:

Java Example