• 04-22-2010
matthayzon89
Hello all,
I have always had problems with loop tracking problems, I seem to understand how the loop runs and when it ends and the general idea of how it works. However, when I take a programming test and I need to track the output of a short loop, I fail most of the time. Can someone please help me? or give me some strategy tips?

The problem below is an example, I need to find the output of SUM without a computer, just using logic and a pencil and paper.

This is what I got for my i, and sum;

i
0
3
9
12

sum:
0
3
6
9
12

So in my attempt: sum= 12 but the correct answer is sum=30.

Code:

```int main () {         int sum=0, i=0; while (i <=12) {           sum = sum +i;  // before this read sum=sum+1 which was a typo:/           i= i+3; } printf("%d", sum);```
• 04-22-2010
hk_mp5kpdw
sum increase by 1 each time through the loop. i increases by 3 each time. Your sum values posted above are thus wrong and you are missing a 6 in your list of i values.
• 04-22-2010
matthayzon89
Darn!

Sorry, there was a typo in the segment of code:(
I edited it, the correct answer for sum=30.

Can someone please help me understand whats going on? Can you basically solve this and think out loud so I can follow your thought pattern and learn from it?
• 04-22-2010
grumpy
Quote:

Originally Posted by hk_mp5kpdw
sum increase by 1 each time through the loop.

No, it does not.
• 04-22-2010
hk_mp5kpdw
Quote:

Originally Posted by grumpy
No, it does not.

It did... in the original version of his post. (He edited it)
• 04-22-2010
hk_mp5kpdw
Not so difficult to follow on paper (values below taken at end of each loop):
Code:

```i    sum 3    0 6    3  (0  +  3) 9    9  (3  +  6) 12  18 (9  +  9) 15  30 (18 + 12)```
• 04-22-2010
matthayzon89
Quote:

Originally Posted by hk_mp5kpdw
Not so difficult to follow on paper (values below taken at end of each loop):
Code:

```i    sum 3    0 6    3  (0  +  3) 9    9  (3  +  6) 12  18 (9  +  9) 15  30 (18 + 12)```

Thank you very much! That clarifies. I finally get it!

Thanks again man, take care.
• 04-22-2010
matthayzon89
Also, two NOOB questions:)

a) What is the format to randomize a number? for example a number between 15-100.

would it be rand(15)%100?

b)How come the answer to this is 15?

13+20/(5+3%4)

I get 4.125 for my answer:

1)3%4=3
2)5+3=8
3)13+20=33
4)33/8=4.125