write a program in java to enter number one by one and calculate and print it's sum and average,using while loop
Answers
Explanation:
In this program, you'll learn to calculate the sum of natural numbers using for loop and while loop in Java.
To understand this example, you should have the knowledge of the following Java programming topics:
Java for Loop
Java while and do...while Loop
The positive numbers 1, 2, 3... are known as natural numbers and its sum is the result of all numbers starting from 1 to the given number.
For n, the sum of natural numbers is:
1 + 2 + 3 + ... + n
Example 1: Sum of Natural Numbers using for loop
public class SumNatural {
public static void main(String[] args) {
int num = 100, sum = 0;
for(int i = 1; i <= num; ++i)
{
// sum = sum + i;
sum += i;
}
System.out.println("Sum = " + sum);