This is an exercise using a while loop Input an integer n from the keyboard. Calculate the sum of the first n integers. So if n=10, the answer should be 55 (because 1+2+3+4+5+6+7+8+9+10=55)
Code language: Java
Java program to
find the sum of first n numbers using while
loop:
Step-1: Declare and initialize the required variables- n, sum=0,
i=1.
Step-2: Ask the user to enter a integer number and store it in the
variable n.
Step-3: Use the while loop to check if i (i.e. 1) is less than or
equal to n,
3.1: If true, then add the value of i to sum, and increment the
value of i by 1, then again check the condition i<=n, if true
repeat the step-3.1.
3.2: Once it becomes false, then come out of the while loop and
execute the next statement following the while loop i.e. the print
the sum statement.
The complete program is shown below:
import java.util.Scanner;
public class Main
{
public static void main(String[] args)
{
int n, i=1, sum=0;
System.out.print("Enter the
integer: ");
Scanner scan=new
Scanner(System.in);
n= scan.nextInt();
while(i<=n)
{
sum=sum+i;
i++;
}
System.out.println("Sum of the
first " + n + " numbers is: " +sum);
}
}
The screenshot of the complete program along with the output and explanation is shown below:
Output-1:
Output-2:
Get Answers For Free
Most questions answered within 1 hours.