We help IT Professionals succeed at work.

# Learning Do While Loop Calculation

on
369 Views
In the code below, I was expecting that the final output of the variable "sum" should be 37. After the variable "count" is iterated to value 11, I assumed that Do-While loop should be terminated. I know that count++ <11 means - compare first, then iterate; but I am unable to find a way to calculate the accurate value of "sum". Can you please let me know how the variable "sum" is 48?

Can you also suggest me some tips/tricks/methods you use as a programmer to calculate this kind of problem manually (without compiling and running it)? I would be approaching this kind of problems during exam, so I am trying to find an efficient way to solve this kind of problem.

Code Given:

``````public class MyClass
{

public static void main(String args[])
{
int count = 0, sum = 0;
do
{
System.out.println("count : " + count + " sum : " + sum);
if(count % 3 == 0) continue;
sum+=count;
//System.out.println("count : " + count + " sum : " + sum);
}
while(count++ < 11);
System.out.println(sum);  }
}
``````

Output:

``````count : 0 sum : 0
count : 1 sum : 0
count : 2 sum : 1
count : 3 sum : 3
count : 4 sum : 3
count : 5 sum : 7
count : 6 sum : 12
count : 7 sum : 12
count : 8 sum : 19
count : 9 sum : 27
count : 10 sum : 27
count : 11 sum : 37
48
``````

Comment
Watch Question
Commented:
This problem has been solved!
###### Why Experts Exchange?

Experts Exchange always has the answer, or at the least points me in the correct direction! It is like having another employee that is extremely experienced.

Jim Murphy
Programmer at Smart IT Solutions

Deciding to stick with EE.

Mohamed Asif

Being involved with EE helped me to grow personally and professionally.

Carl Webster
CTP, Sr Infrastructure Consultant