Cumulative sum with for loop - Java Language Basics

Java examples for Language Basics:for

Description

Cumulative sum with for loop

Demo Code

public class Main {
  public static void main(String args[]) {
    int i, n = 10;
    int cumulLoop = 0;
    for (i = 0; i < n; i++) {
      cumulLoop += i;/*from ww  w  .ja va2 s.  c  o  m*/
    }
    int cumul = (n * (n - 1)) / 2; // closed-form solution
    System.out.println(cumulLoop + " closed-form:" + cumul);
  }
}

Result


Related Tutorials