Java while loop calculate the sum of the integers from 1 to 10

Question

We would like to calculate the sum of the integers from 1 to 10.

public class Main {
  public static void main(String[] args) {
    int sum = 0;/*from  w  ww . j  a v  a2  s  . c o  m*/
    int x = 1;

    //your code here
    
    
    System.out.printf("The sum is: %d%n", sum);
  }
}


// Calculate the sum of the integers from 1 to 10  
public class Main {
  public static void main(String[] args) {
    int sum = 0;
    int x = 1;

    while (x <= 10) // while x is less than or equal to 10
    {
      sum += x; // add x to sum
      ++x; // increment x
    }

    System.out.printf("The sum is: %d%n", sum);
  }
}



PreviousNext

Related