Solved ProgramsICSEClass 9Computer Applications

Sum of First n Natural Numbers in Java (Loop and Formula)

Find the sum of the first n natural numbers in Java with a for loop, a while loop and the formula n(n + 1)/2, with a dry run and the sums of even numbers, odd numbers, squares and cubes.

4 min read
Solved Programs

Finding the sum of the first n natural numbers is the classic first loop program in ICSE Class 9 Computer Applications. It teaches how an accumulator variable builds up a total. This post solves it with a for loop, a while loop and the formula n(n + 1)/2, and then extends it to the sums of even numbers, odd numbers, squares and cubes.

What are natural numbers?

Natural numbers are the counting numbers 1, 2, 3, 4 and so on. The sum of the first n natural numbers is 1 + 2 + 3 + … + n. For n = 10 the sum is 55.

Program 1: using a for loop

The variable sum starts at 0 and the loop adds each number from 1 to n to it.

import java.util.*;

class SumNatural
{
    public static void main(String[] args)
    {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter n: ");
        int n = sc.nextInt();

        int sum = 0;
        for (int i = 1; i <= n; i++)
        {
            sum = sum + i;
        }
        System.out.println("Sum of the first " + n + " natural numbers = " + sum);
    }
}

Output:

Enter n: 10
Sum of the first 10 natural numbers = 55

Dry run for n = 5

i     sum before   sum after
1     0            1
2     1            3
3     3            6
4     6            10
5     10           15
Loop ends when i becomes 6, so the sum is 15

Program 2: using a while loop

The same logic with a while loop: initialise the counter before the loop, test it in the condition and increase it at the end of the body.

import java.util.*;

class SumWhile
{
    public static void main(String[] args)
    {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter n: ");
        int n = sc.nextInt();

        int i = 1, sum = 0;
        while (i <= n)
        {
            sum += i;
            i++;
        }
        System.out.println("Sum = " + sum);
    }
}

Program 3: using the formula n(n + 1)/2

The young mathematician Gauss noticed that pairing the first and last numbers gives the same total each time: 1 + 100, 2 + 99, 3 + 98… For the first n numbers there are n/2 such pairs of n + 1, so the sum is n(n + 1)/2. The formula needs no loop at all. long is used so that large values of n do not overflow.

import java.util.*;

class SumFormula
{
    public static void main(String[] args)
    {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter n: ");
        long n = sc.nextLong();

        long sum = n * (n + 1) / 2;
        System.out.println("Sum of the first " + n + " natural numbers = " + sum);
    }
}

Output:

Enter n: 100000
Sum of the first 100000 natural numbers = 5000050000

Sum of even numbers, odd numbers, squares and cubes

Examiners often change the series slightly. One loop can find all four sums:

import java.util.*;

class SumVariants
{
    public static void main(String[] args)
    {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter n: ");
        int n = sc.nextInt();

        int even = 0, odd = 0;
        long squares = 0, cubes = 0;
        for (int i = 1; i <= n; i++)
        {
            if (i % 2 == 0)
                even += i;
            else
                odd += i;
            squares += (long) i * i;
            cubes += (long) i * i * i;
        }
        System.out.println("Sum of even numbers up to " + n + " = " + even);
        System.out.println("Sum of odd numbers up to " + n + " = " + odd);
        System.out.println("Sum of squares = " + squares);
        System.out.println("Sum of cubes = " + cubes);
    }
}

Output for n = 10:

Sum of even numbers up to 10 = 30
Sum of odd numbers up to 10 = 25
Sum of squares = 385
Sum of cubes = 3025

The formulas to check your answers are: sum of squares = n(n + 1)(2n + 1)/6 and sum of cubes = [n(n + 1)/2]².

Variable description

  • n — int — how many natural numbers to add
  • i — int — loop counter that takes the values 1 to n
  • sum — int — accumulator that holds the running total

Common mistakes

  • Not initialising sum to 0 before the loop.
  • Writing i < n instead of i <= n, which leaves out the last number.
  • Declaring sum inside the loop, which resets it to 0 on every pass.
  • Using an int for large n: the sum of the first 100000 numbers does not fit in an int.

Practice questions

  1. Find the sum of the natural numbers from m to n, both entered by the user.
  2. Find the sum of the series 1 + 1/2 + 1/3 + … + 1/n (use a double).
  3. Print the first n natural numbers and their sum on separate lines.
  4. Find the average of the first n natural numbers.

For more loop practice see Loops in Java for ICSE Class 9, the series programs and the ICSE Class 9 hub.