Java Program to Display Numbers and Sum of First N Natural Numbers


Natural numbers are all positive integers or whole numbers that range between 1 to infinity. In this article, we are going to see how to display numbers as well as the sum of the first N natural numbers in java where n is defined by the user. Mathematically speaking, the sum of 1st N natural numbers is given by the formula −

Sum = n * (n+1) / 2

In order to implement this in java, there are mainly 3 methods with a slight difference.

1. Using a for loop or do while loop or while loop

The approach here is straightforward. We take an input from the user to determine the value of n. A variable sum is initialized as 0. We then run a for loop that goes from 1 to n. In each iteration the value of the loop variable is printed and the value is added to the sum variable. After the loop is terminated, we then print the sum.

In this method, the time complexity is O(n) where n is the natural number till where all computation has to be performed. The reason for this is that the loop runs n times to calculate the sum and print the first n natural numbers.

Example

public class Main {
   public static void main(String[] args) {
   
      int n = 5; // stores the value of n that user inputs
      int sum = 0;  //stores the sum
   
      System.out.print("The first " + n + " natural numbers are:");
      for (int i = 1; i <= n; i++) {
         /* For loop goes from 1 to n, prints each number during the iteration and keeps adding it to the sum variable */
   
         System.out.print(i + " ");  
         sum += i;
      }
      System.out.println("");
      System.out.println("\n The sum of the first " + n + " natural numbers is: " + sum);  //print the sum
   }
}

Output

The above program will produce the following output -

The first 5 natural numbers are:1 2 3 4 5 
The sum of the first 5 natural numbers is: 15

2. Using the Mathematical Formula

The approach is quite similar as above except for a small difference that amounts to a relatively higher accuracy. Instead of repeatedly adding numbers to the sum during the iterations, we are only printing the natural numbers in the loop whereas the sum is calculated before the loop using the formula SUM = N * (N+1)/2

In this method, time complexity is O(1) because the program computes the sum of the 1st n natural numbers via the formula mentioned above. This takes a constant amount of time irrespective of the value of n. However the overall time complexity of the program still remains O(n) as the program uses a for loop to display the numbers and is running n times.

Example

public class Main {
   public static void main(String[] args) {
      int n = 5; // stores the value of n that user
      int sum = (n * (n + 1)) / 2;  // calculate the sum using formula method
      System.out.print("The first " + n + " natural numbers are:");
      for (int i = 1; i <= n; i++) {
         /* For loop goes from 1 to n, prints each number during the iteration */
         System.out.print(i + " ");  
   
      }
      System.out.println(" ");  
      System.out.println("\nThe sum of the first " + n + " natural numbers is: " + sum);  //print the sum
   }
}

Output

The above program will produce the following output -

The first 5 natural numbers are:1 2 3 4 5  
The sum of the first 5 natural numbers is: 15

3. Using Recursion

The approach here is such that a user defined function sumOfNaturals(int n) recursively calls itself till the base of the recursion is reached. The base here is when n is equal to 1. If the base is not reached, the function returns n + result of the function call to sumOfNaturals(n-1). The for loop does the work of printing the numbers.

The time complexity here is O(n) where n corresponds to the natural numbers to be displayed and summed up. The reason behind this is the function sumofNaturals(n) performs a single addition operation and single function call for each value of n from n down to 1. Therefore, the number of operations performed is proportional to n.

Example

public class Main {
   public static int sumOfNaturals(int n) {
   
      if (n == 1) {
         return 1;
      }
      return n + sumOfNaturals(n-1);
   }
   
   public static void main(String[] args) {
      int n = 5;
      int sum = sumOfNaturals(n);
      System.out.print("The first " + n + " natural numbers are: ");
      for (int i = 1; i <= n; i++) {
         System.out.print(i + " ");
      }
      System.out.println();
      System.out.println("\nThe sum of the first " + n + " natural numbers is: " + sum);
   
   }
}

Output

The above program will produce the following output -

The first 5 natural numbers are: 1 2 3 4 5 
The sum of the first 5 natural numbers is: 15

Conclusion

Writing a program in java in order to display the 1st n natural numbers and to calculate their sum at the same time is a great starting point for those learning java. Basic concepts such as loops, performing arithmetic operations and recursion are demonstrated here. The 1st Method makes use of a fall loop to display and compute the sum. The second method makes use of the mathematical formula to find the sum and the for loop to print all the numbers. The 3rd method makes use of iteration to compute the sum while the rest remains the same.

All methods have an overall linear time complexity. The 1st method has O(n) for summation and displaying, the 2nd has O(1) for summing but O(n) for displaying the numbers. The 3rd method is O(n) for printing and O(n) for computing which amounts to O(n) overall.

Updated on: 10-Mar-2023

546 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements