java program to calculate the sum of natural numbers

Write a java program to calculate the sum of natural numbers using for loop

The natural numbers are the numbers that include all the positive integers from 1 to infinity. For example, 1, 2, 3, 4, 5, ...., n. When we add these numbers together, we get the sum of natural numbers.

In this section, we will create the following programs:

  • Java program to find the sum of the first 100 natural numbers
  • Java program to find the sum of n natural numbers
  • Java program to find the sum of n natural numbers using the function

We can also find the sum of n natural number using the mathematical formula:

Sum of n natural numbers = n*(n+1)/2

Suppose we want to find the sum of the 100 natural numbers. By putting the value in the above formula, we get:

Sum = 100*100+1/2 = 100*50.5 = 5050

Here, we are going to use for loop to find the sum of natural numbers.

  • Program:

public class SumNatural {

    public static void main(String[] args) {

        int num = 110, sum = 0;

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

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

  • Output:

Sum = 6105

  • Visit:

Java program to print an Integer Here
Java program to add two integers Here
Java program to find ASCII value of a character Here
Java program to compute quotient and remainder Here
Java program to swap two numbers Here
Java program to check whether a given number is even or odd Here
Java program to check whether an alphabet is vowel or consonant Here 
Java program to find the largest among three numbers Here
Java program to find all roots of a quadratic equation Here
Java program to check leap year Here
Write a java program to multiply two floating point numbers Here
Java program to check whether a number is positive or negative Here
Java program to check whether a character is alphabet or not Here

0 comments