Java Program to Calculate the Sum of Natural Numbers

In this Java tutorial, you’ll learn how to Calculate the Sum of Natural Numbers using the Java programming language. 

How to calculate the sum of natural numbers in JAVA? 

Example 1: using for loop 

RUN CODE SNIPPET
public class Main 
 { 
    public static void main(String[] args)  
    { 
        int num = 50, sum = 0; 
        for(int i = 1; i <= num; ++i) 
        { 
            sum += i; 
        } 
        System.out.println("Sum = " + sum); 
    } 
}

OUTPUT 

Sum = 1275

In the above program, the added value is stored in the variable sum. The loop adds the value from 1 to the given number 50. 

Example 2: using while loop 

RUN CODE SNIPPET
public class Main  
{ 
    public static void main(String[] args)  
    { 
        int num = 5, i = 1, sum = 0; 
        while(i <= num) 
        { 
            sum += i; 
            i++; 
        } 
        System.out.println("Sum = " + sum); 
    } 
}

OUTPUT 

Sum = 15

In the above example, the while loop executes until the “i<=num” condition is true. 

Share:

Leave A Reply

Your email address will not be published. Required fields are marked *

You May Also Like

Java is a popular programming language that is used to develop a wide range of applications. If you are a...
  • Java
  • March 6, 2023
Java is a programming language and computing platform that is used to create various types of applications. It is used...
  • Java
  • March 6, 2023
In this post, you’ll learn how to download and install JUnit in Eclipse so that you can use in your...
  • Java
  • October 9, 2022