Use the while loop to calculate sum in Java

Description

The following code shows how to use the while loop to calculate sum.

Example


public class Main {
  public static void main(String[] args) {
    int limit = 20;
    int sum = 0;/*from   w  ww.j a va  2 s  . c o  m*/
    int i = 1;

    while (i <= limit) {
      sum += i++;
    }
    System.out.println("sum = " + sum);
  }
}

The code above generates the following result.





















Home »
  Java Tutorial »
    Java Language »




Java Data Type, Operator
Java Statement
Java Class
Java Array
Java Exception Handling
Java Annotations
Java Generics
Java Data Structures