Sum of the First 50 Natural Numbers
In this programme, you'll learn how to use Java's for loop and while loop to calculate the sum of natural integers.
- Using For Loop
- Using While Loop
Using Java For Loop
The simplest way to find the sum of natural numbers is to use Java for loop.
Consider we want to Calculate the Sum of the first 50 Natural numbers.
Algorithm:
Using Java looping instructions, the following approach may be used to find the sum of the first N natural numbers.
- Start.
- Read the limit.
- Start with a value of sum = 0.
- Set the value of i to 1.
- Determine whether i is less than or equal to the limit. If the answer is no, proceed to step 8
- Add the value of i to the sum.
- Go to step 5 after incrementing i.
- Calculate the sum and print the value.
- Exit.
Code:
public class SumForLoop {
public static void main(String[] args) {
int limit = 50, sum = 0;
// loop terminates when the condition returns false
for(int i = 1; i <= limit; ++i)
{
//Adding the value of sum and value of i
sum += i;
}
// prints the value of the final sum
System.out.println("The Sum of the first 50 Natural Numbers is = " + sum);
}
}

You can also try this code with Online Java Compiler
Run Code
Output:
The Sum of the first 50 Natural Numbers is = 1275
Using Java While Loop
The while loop has been used in place of the for loop in the following example. The while loop continues to run until the condition i< = limit is no longer valid. It works out the sum of natural numbers up to a certain limit.
Code:
public class SumWhileLoop {
public static void main(String[] args) {
int limit = 50, i = 1, sum = 0;
// loop terminates when the condition results false
while(i <= limit)
{
sum += i; //Adding the value of sum and i
i++; //incrementing value of i
}
System.out.println("The Sum of first 50 Natural Numbers is =" + sum);
}
}

You can also try this code with Online Java Compiler
Run Code
Output:
The Sum of first 50 Natural Numbers is =1275

You can also try this code with Online Java Compiler
Run Code
Sum of n Natural Numbers
The programme below calculates the sum of n natural numbers. We've used the identical while loop in this programme as we did in the last one. We've additionally taken two user inputs, namely i and limit. The initial value is variable i, while the variable limit is the final value. For example, we can use this approach if we wish to find the sum of natural numbers from 10(i) to 100(limit).
Code:
import java.util.Scanner;
public class SumOfnNaturalNumbers {
public static void main(String[] args)
{
int end, start, sum = 0;
//object of Scanner class
Scanner sc = new Scanner(System.in);
System.out.print("Starting from: ");
//takes an integer as input for starting
start = sc.nextInt();
System.out.print("End value: ");
//takes an integer as input for ending
end = sc.nextInt();
while(start<= end)
{
//adding the value of start and sum variable
sum = sum + start;
//incrementing the value of start
start++;
}
//prints the final value of the sum
System.out.println("The Sum of Natural Numbers = " + sum);
}
}

You can also try this code with Online Java Compiler
Run Code
Output:
Starting from: 1
End value: 50
The Sum of Natural Numbers = 1275

You can also try this code with Online Java Compiler
Run Code
Also see, Duck Number in Java
Sum of Natural Numbers using Java Methods
We've been using while and for loops wherever and whenever we've needed to repeat something. We can also find the Sum of first n Natual Numbers by creating and using methods in java.
There are two ways to Find the sum using methods:
- By using the Iterative method,
- By using the Recursive method
Using Java Iterative method
We used the function to find the sum of n natural numbers in the following programme.
Code:
public class SumIterativeMethod {
//method that returns the sum
static int NumberSum(int limit)
{
int sum = 0;
//executes until the condition returns false
for (int i = 1; i <= limit; i++)
//adding the value of i and the sum variable
sum = sum + i;
return sum;
}
//main method
public static void main(String args[])
{
int limit = 50;
//calling method and prints the sum
System.out.println("The Sum of the given Natural Numbers is: "+NumberSum(limit));
}
}

You can also try this code with Online Java Compiler
Run Code
Output:
The Sum of the given Natural Numbers is: 1275

You can also try this code with Online Java Compiler
Run Code
Using Java Recursive Method
Let's look at one of the most wondering things a method may do: call itself to perform the solution to the smaller version of the same problem.
Algorithm:
- A variable number is used to hold the number whose sum needs to be found.
- The SumNatural() function is initially called from the main() function with the value 50 as an input.
- The limit (50) is added to the SumNatural result (49).
- The number 49 is sent to the following function call from SumNatural() to SumNatural(), and it is added to the result of SumNatural(48). This method is repeated till num equal to zero.
- When num equals 0, no recursive call is made, and the sum of integers is returned to the main() function.
Code:
public class SumRecursionMethod {
//main method
public static void main(String[] args) {
int number = 50;
int sum = SumNatural(number);
System.out.println("The Sum of the Natural Numbers is = " + sum);
}
//recursive method that returns the sum
public static int SumNatural(int num) {
if (num != 0)
return num + SumNatural(num - 1);
else
return num;
}
}

You can also try this code with Online Java Compiler
Run Code
Output:
The Sum of the Natural Numbers is = 1275

You can also try this code with Online Java Compiler
Run Code
You can easily run this code yourself with java online compiler.
Also check out Addition of Two Numbers in Java here.
FAQs
-
What is Method in Java?
A method is a segment of code that only executes when it is invoked. Parameters are data that can be passed into a method. Methods, often known as functions, are used to carry out specific tasks.
-
What do you mean by Recursion?
The technique of making a function call itself is known as recursion. This strategy allows you to break down complex difficulties into more minor, easier-to-solve problems.
-
How many types of Recursion are there?
There are two sorts of recursion: one in which a function calls itself from within itself, and the other in which multiple functions call each other mutually. The first is known as direct recursion, whereas the second is known as indirect recursion.
-
What is an Infinite Loop?
An infinite loop (also known as an endless loop) is a piece of code that continues indefinitely because it lacks a functional exit.
-
What is the critical difference between While and For loop in Java?
The difference between a for loop and a while loop is that in a for loop, the number of iterations to be performed is already known and is used to obtain a particular result, whereas, in a while loop, the command runs until a specific condition is met and the statement is proven untrue.
- What do you mean by instance variable in Java?
When we have to instantiate an object, instance variables are created and are accessible to all constructors, methods, and blocks in the class.
Key Takeaways
This article has discussed the Java Program to find the sum of natural numbers by various approaches like the loop, iterative methods, Recursive Methods, etc.
You can also learn Object-Oriented Properties of Java such as Abstraction in java, Inheritance in Java. Properties like association, aggregation, and composition.
Check out this problem - Subarray Sum Divisible By K
Visit Coding Ninjas Studio, our practice platform, to practice top problems, take mock tests, read interview experiences, and much more technical stuff.
We wish you Good Luck! Keep coding and keep reading Ninja!!