Here we are explaining how to write a java program to find out the sum of first n natural numbers. So first we have to read the value of n from the user. Then by using a while loop
we can find out the sum of 1 to n numbers.
The syntax of the while loop
is shown below.
while(condition)
{
statements;
}
In while loop,the statements are executed repeatedly when it satisfy the condition.
First, we have to declare the class sumOfNatural .Then declare the variables n,i,sum as an integer.set i=1 and sum=0.Create an object of the Scanner class as s. Read the limit of the number into the variable n.By using a while loop check i<=n,then calculate sum=sum+i.Increment i by one. Then display the sum of first n natural numbers as a sum.
STEP 1: Declare the class SumOfNatural with a public modifier.
STEP 2: Open the main() to start the program, Java program execution starts with the main()
STEP 3: Declare the integer variables n,i,sum.Set sum=0.
STEP 4: Read the limit of the number into the variable n.
STEP 5: By using a while loop check i<=n do step 6.
STEP 6: Calculate sum=sum+i.
STEP 7: Increment i by one and do step 5.
STEP 8: Display sum.
import java.util.Scanner;
public class SumOfNatural{
public static void main(String args[]){
int n, i = 1 ;
int sum = 0;
Scanner s = new Scanner(System.in);
System.out.println("Enter the limit of the number :");
n = s.nextInt();
while(i <= n)
{
sum = sum +i;
i++;
}
System.out.println("The Sum of "+n+" numbers is :"+sum);
}
}
Enter the limit of the number :4 Sum of 4 numbers is :10