Display Numbers and Sum of First N Natural Numbers in Java



Natural numbers are all positive integers or whole numbers that range between 1 to infinity. In this article, we will see how to find the sum of the first N natural numbers in Java, where N is the integer up to which we need to add all the numbers starting from 1.

Example Scenario:

Input: num = 5
Output: sum = 15
sum = 1 + 2 + 3 + 4 + 5

Using a for loop

In this approach, initialize a variable with 0 to store the sum. Then, run a for loop that goes from 1 to a given number. During each iteration, the value of the loop variable is printed and the value is added to get the sum. After the loop gets terminated, print the sum.

The time complexity will be 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

Following Java program shows how to find sum of first N natural numbers using for loop.

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

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

Using the Mathematical Formula

The approach is quite similar to the above except for a small difference that amounts to a relatively higher accuracy. Instead of repeatedly adding numbers during the iterations, we will calculate the sum using a mathematical formula.

The Mathematical formula to find the sum of 1st N natural numbers is ?

Sum = N * (N+1)/2

Here, the time complexity will be O(1) because the program will take 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

Let's see the practical demonstration of the above approach ?

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

The above program will produce the following output ?

The first 8 natural numbers are: 1 2 3 4 5 6 7 8 
The sum of the first 8 natural numbers is: 36

Using Recursion

Create a user-defined function that recursively calls itself till the base of the recursion is reached. The base here is when the given number becomes equal to 1. If the base is not reached, this function keeps adding all natural numbers till the given number.

The time complexity here is O(n) where n corresponds to the natural numbers to be displayed and summed up.

Example

Here, we are using recursion to calculate sum of first N natural numbers.

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("\nThe sum of the first " + n + " natural numbers is: " + sum);
   }
}

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
Updated on: 2024-08-16T07:34:54+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements