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

In this Java program, we will learn how to find the GCD of two numbers using Java.  GCD (Greatest Common...
  • Java
  • December 3, 2024
In this Java Program, you’ll learn how to swap two numbers using the Java programming language.  How to Swap Two...
  • Java
  • December 2, 2024
In this Java program , we will learn how to Find Largest Element in an Array in your Java program.   How to Find Largest Element...
  • Java
  • December 2, 2024