Find Sum of Natural Numbers Using While Loop in Java



The sum of natural numbers can be calculated using different Iterative Statements in Programming Languages. Iterative Statements are statements that execute a particular set of code lines until the condition in the loop statement fails. In this article, we will discuss how to calculate the sum of natural numbers using a while-loop which is an iterative statement in Java.

Sum of Natural Numbers

The sum of natural numbers generally indicates the total sum of elements from 1 to n. Mathematically it can be represented as follows

Sum of n Natural Numbers =  1+2+3+.........+(n-2) + (n-1) + n                           

Problem Statement

Write a program in Java to find the sum of natural numbers using a while loop.

Input

5

Output

Sum of natural numbers up to 5 is :15

Explanation:

The sum of natural numbers from 1 to 5 = 1+ 2+ 3+ 4+ 5 = 15.

While loop statement in Java

A while loop in Java language is one of the iterative statements present that allows a set of code blocks to be executed repeatedly until the condition becomes false.

Syntax

initilaze condition variable
while (condition)
{
   // statements
   Update condition variable;
}

Steps to find sum of natural numbers

Following are the steps to find the sum of natural numbers

  • Initialize three variables that denote the number of natural numbers to find the sum, a counter variable, a variable that stores the sum of natural numbers.
  • Use the while and perform the addition of the sum of natural numbers until ?n'.
  • Print the total sum of natural numbers.

Java program to find sum of natural numbers

In this below we use a while loop in Java to find the sum of natural numbers. We declared a variable n for getting a sum of up to n numbers. The ?i' is the counter variable used. We use the while loop and iterate from i to n sum up all the values and store in sum variable. At last, the value of the sum variable to get the output.

import java.util.*;
public class Main {
   public static void main(String[] args) {
      int n= 7,  i = 1,sumofDigits = 0;
      while (i <= n) { 
         // checking the condition if it satisfies then the statements inside loop are executed
         sumofDigits = sumofDigits + i; 
         // performing addition to sum as the number should be added to sum
         i++;
         // Incrementing  the variable used in condition
      }
      System.out.println("Sum of natural numbers up to 7 is :" +sumofDigits);
   }
}

Output

Sum of natural numbers up to 7 is :28

Time Complexity: O(N)

Auxiliary Space: O(1)

Thus in this article, we have learned how to use the while-loop concept in Java programming language to calculate the sum of n natural numbers.

Updated on: 2024-09-05T11:23:05+05:30

594 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements