We help IT Professionals succeed at work.
Get Started

Learning Do While Loop Calculation

techbro
techbro asked
on
369 Views
Last Modified: 2012-05-11
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);  } 
}

Open in new window


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

Open in new window


Thanks in Advance!
Comment
Watch Question
This problem has been solved!
Unlock 2 Answers and 9 Comments.
See Answers
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

When asked, what has been your best career decision?

Deciding to stick with EE.

Mohamed Asif
Technical Department Head

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

Carl Webster
CTP, Sr Infrastructure Consultant
Ask ANY Question

Connect with Certified Experts to gain insight and support on specific technology challenges including:

  • Troubleshooting
  • Research
  • Professional Opinions
Did You Know?

We've partnered with two important charities to provide clean water and computer science education to those who need it most. READ MORE