Presentation is loading. Please wait.

Presentation is loading. Please wait.

Common pattern/tool: Accumulator loops

Similar presentations


Presentation on theme: "Common pattern/tool: Accumulator loops"— Presentation transcript:

1 Common pattern/tool: Accumulator loops
HINT: Exam scores homework problem!! int sum = 0; // initialize these OUTSIDE loop int count = 0; int biggest = -1; for (int i = 1; i <= 1000; i++) { sum = sum + i; // update each of these INSIDE loop count++; if (i > biggest) { // unlike sum and count, we only update biggest biggest = examscore; // some of the time (i.e., when we see a number } // that is bigger than previous biggest } double average = sum/count; println("The sum is " + sum); Accumulator variable: A variable that keeps some progress and is updated repeatedly until loop is finished. The sum in the above code is a cumulative sum. Accumulator variables must be declared outside the loops that update them, so that they will still exist after the loop.


Download ppt "Common pattern/tool: Accumulator loops"

Similar presentations


Ads by Google