You are here:   HomeJava ProgrammingControl Structures in JavaPrime Number Program in Java Using BufferedReader Example.
by Dinesh Thakur Category: Control Structures

In this example, the sum of first 10 natural numbers is displayed. First, input the value of n (10 in this case) i.e. number of natural numbers whose sum is to be calculated. Then, after initializing the variables i to 1 and sum to 0, we enter the do-while loop. The execution of the body of loop continues as long as condition (i<=n) evaluates to true. When variable 1’s is value becomes 11, the condition becomes false and this terminates the do-while loop and program execution continues with the next statement after the loop which displays the sum of first 10 natural numbers.

//Program to Find Sum of First N Natural Numbers

 import java.util.Scanner; //Program uses Scanner class
public class SumNatural
     public static void main(String[] args)
        int n,i=1,sum=0;
        Scanner input=new Scanner(;
        System.out.print("Enter Number :");
                 i +=1;
            }   while(i<=n);
                 System.out.print("Sum of First " + n + " Numbers = "+sum);

Sum of First N Natural Numbers

Subscribe To Free Daily Newsletter!

Get Free News Updates Delivered Directly To Your Inbox
About Dinesh Thakur

Dinesh ThakurDinesh Thakur holds an B.SC (Computer Science), MCSE, MCDBA, CCNA, CCNP, A+, SCJP certifications. Dinesh authors the hugely popular Computer Notes blog. Where he writes how-to guides around Computer fundamental , computer software, Computer programming, and web apps. For any type of query or something that you think is missing, please feel free to contact us.

What's New and Popular

Popular Article