Java Program to Find Sum of Natural Numbers using While Loop

This is a Java Program to Find Sum of Natural Numbers Using While Loop.

Enter the number upto which you want to calculate the sum. Now we use while loops till the given number to get the desired output.

Here is the source code of the Java Program to Find Sum of Natural Numbers Using While Loop. The Java program is successfully compiled and run on a Windows system. The program output is also shown below.

  1. public class Natural 
  2. {
  3.     public static void main(String args[])
  4.     {
  5.         int x, i = 1 ;
  6.         int sum = 0;
  7.         System.out.println("Enter Number of items :");
  8.         Scanner s = new Scanner(System.in);
  9.         x = s.nextInt();
  10.         while(i <= x)
  11.         {
  12.             sum = sum +i;
  13.             i++;
  14.         }
  15.         System.out.println("Sum of "+x+" numbers is :"+sum);
  16.     } 
  17. }

Output:

$ javac Natural.java
$ java Natural
 
Enter Number of items :
55
Sum of 55 numbers is :1540

Sanfoundry Global Education & Learning Series – 1000 Java Programs.

advertisement

Here’s the list of Best Books in Java Programming, Data Structures and Algorithms.

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
I’m Manish - Founder and CTO at Sanfoundry. I’ve been working in tech for over 25 years, with deep focus on Linux kernel, SAN technologies, Advanced C, Full Stack and Scalable website designs.

You can connect with me on LinkedIn, watch my Youtube Masterclasses, or join my Telegram tech discussions.

If you’re in your 40s–60s and exploring new directions in your career, I also offer mentoring. Learn more here.