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
advertisement

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

If you find any mistake above, kindly email to [email protected]

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
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.