Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Sum of Natural Numbers
3.
Sum of the First 50 Natural Numbers
3.1.
Using Java For Loop
3.1.1.
Consider we want to Calculate the Sum of the first 50 Natural numbers. Algorithm:
3.1.2.
Code:
3.1.3.
Output:
3.2.
Using Java While Loop
3.2.1.
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:
3.2.2.
Output:
4.
Sum of n Natural Numbers
4.1.
Code:
4.2.
Output:
5.
Sum of Natural Numbers using Java Methods
5.1.
Using Java Iterative method
5.1.1.
Code:
5.1.2.
Output:
5.2.
Using Java Recursive Method
5.2.1.
Algorithm:
5.2.2.
Code:
5.2.3.
Output:
6.
FAQs
7.
Key Takeaways
Last Updated: Mar 27, 2024

Program to find Sum of Natural Numbers

Master Power BI using Netflix Data
Speaker
Ashwin Goyal
Product @
18 Jun, 2024 @ 01:30 PM

Introduction

Programming (or writing programmes) is a creative and satisfying activity. You can build programmes for various purposes, including making a living, solving a challenging data analysis challenge, having fun, or assisting someone else with difficulty.

Our computers are quick and have a lot of memory, and they could be handy to us if we only knew how to communicate with them and tell them what we want them to "do next." We could tell the machine to perform repetitious work on our behalf if we learned the programming language.

Computers are not yet clever enough to comprehend straightforward human language. So, to do a task using a computer, we must build a programme. Here we will learn about a program to find the sum of natural numbers.

Sum of Natural Numbers

Natural numbers are made up of all positive integers from 1 to infinity. For e.g., 1, 2, 3, 4, 5……..n.  We get the sum of natural numbers when we add these integers together.

In this programme, you'll learn how to use Java's for loop and while loop to calculate the sum of natural integers.

Also, We will learn how to find the sum of Natural numbers by using functions/methods in Java.

To follow these examples, you need to be familiar with the following Java programming concepts:

  1. Loops in Java
  2. Methods in Java
  3. Concept of Recursion

Here is a roadmap of what we will cover in this article.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

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.

  1. Start.
  2. Read the limit.
  3. Start with a value of sum =  0.
  4. Set the value of i to 1.
  5. Determine whether i is less than or equal to the limit. If the answer is no, proceed to step 8
  6. Add the value of i to the sum.
  7. Go to step 5 after incrementing i.
  8. Calculate the sum and print the value.
  9. 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);
    }
}

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);
   }
}

Output:

The Sum of first 50 Natural Numbers is =1275

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);  
}  
}  

Output:

Starting from: 1
End value: 50
The Sum of Natural Numbers = 1275

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:

  1. By using the Iterative method,
  2. 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));  
}    
}   

Output:

The Sum of the given Natural Numbers is: 1275

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;
   }
}

Output:

The Sum of the Natural Numbers is = 1275

 

You can easily run this code yourself with java online compiler.

Also check out Addition of Two Numbers in Java here.

FAQs

  1. 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.
     
  2. 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.
     
  3. 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.
     
  4. 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.
     
  5. 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.
     
  6. 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 loopiterative methodsRecursive Methods, etc.

You can also learn Object-Oriented Properties of Java such as  Abstraction in javaInheritance 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!!

 

Previous article
Smallest Element in an Array
Next article
Java Program to Display Even Numbers from 1 to 100
Live masterclass