Write a program in java to find the sum of any 10 numbers using loop
Answers
Answer:
public class Natural
{
public static void main(String args[])
{
int x, i = 1 ;
int sum = 0;
System.out.println("Enter Number of items :");
Scanner s = new Scanner(System.in);
x = s.nextInt();
while(i <= x)
{
sum = sum +i;
i++;
}
System.out.println("Sum of "+x+" numbers is :"+sum);
}
}
Answer:
Sanfoundry
Menu
Java Program to Find Sum of Natural Numbers Using While Loop
« PrevNext »
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.
advertisement
public class Natural
{
public static void main(String args[])
{
int x, i = 1 ;
int sum = 0;
System.out.println("Enter Number of items :");
Scanner s = new Scanner(System.in);
x = s.nextInt();
while(i <= x)
{
sum = sum +i;
i++;
}
System.out.println("Sum of "+x+" numbers is :"+sum);
}
}
Output:
$ javac Natural.java
$ java Natural
Enter Number of items :
55
Sum of 55 numbers is :1540
Explanation:
HOPE IT HELPED YOU