Find Sum of n Numbers in Java

You are currently viewing Find Sum of n Numbers in Java

Hi reader, If you looking to know the concept of Find Sum of n Numbers in Java program then read this tutorial to learn about it. Firstly, We will talk about sum of n numbers and how to do a task using the java program? Let’s start the article.

What is sum of n(natural) numbers?

It is nothing but equal to n divided by 2 times the sum of twice the first term. Normally, Natural numbers are all positive integers that start with 1 and end with infinity except 0.

1 + 2 + 3 + ... + n

The formula for finding the sum of n(natural) numbers is shown below for your reference.

[n(n+1)]/2

Here, We can use the for loop and the while loop to find sum of n numbers using java program. Let’s see one by one.

Find Sum of n Numbers in Java

Now, We can use the for loop to execute a task in the below example program.

public class SumNatural {

    public static void main(String[] args) {

        int num = 50, sum = 0;

        for(int i = 1; i <= num; ++i)
        {
            // sum = sum + i;
            sum += i;
        }

        System.out.println("Sum = " + sum);
    }
}

Explanation

Initially, We need to define the variable for the input natural number. After running this program, We will give the input number. After giving the input number, The for loop will start the iteration from i=1 to i<=num.

Finally, The system.out.printIn() function will display the result on the output screen.

Output

The output will provide below for your reference.

Sum = 1275
Read Also : Pascal Triangle in Java

Note

We have already published the article Find Sum of n Numbers in JavaScript. If you want to learn then please refer to the article.

Find Sum of n Numbers in Java

The while loop will help to perform a task in the below program.

public class SumNatural {

    public static void main(String[] args) {

        int num = 75, i = 1, sum = 0;

        while(i <= num)
        {
            sum += i;
            i++;
        }

        System.out.println("Sum = " + sum);
    }
}

Execution

The input number will be stored in the respective variable. After executing the program, The while loop will use to calculate the sum of n numbers. The output will display on the screen using the system.out.printIn() function.

Output

The output of find sum of n numbers in java program will be given below for your reference.

Sum = 2850

Final Words

I hope this article helps you to Find Sum of n Numbers using the Java Program. If you face any problems please let me know via the comment section. Share this article with other Java program developers via social networks. Thank You!

Manoj S

Hi, I'm Manoj working as a part-time blogger in Coding Diksha. Here, I post about programming to help developers.

Leave a Reply