<programming question> Help me understand something...

Darien

Platinum Member
Feb 27, 2002
2,817
1
0
can anyone here explain why the output is 9?

#include <stdio.h>

int main()

{

int n = 0;
int loopcount;

for (loopcount = 1; loopcount <= 3; loopcount++)
while (n++ <= 4)
n += 2*loopcount;

printf("%d\n", n);

return 0;

}

Thanks
 

Cerebus451

Golden Member
Nov 30, 2000
1,425
0
76
Don't forget that the line "while (n++ <= 4)" increments n by 1 every time it is hit. The line "n += 2*loopcount;" only increments n twice (both times incrementing by 2 while loopcount is 1). The while statement is executed 5 times (3 times with loopcount = 1, then once more for loopcount 2 & 3), thus a total of 9.
 

gopunk

Lifer
Jul 7, 2001
29,239
2
0
loopcount = 1
n = 0
---
loopcount = 1
n = 1
enter while loop
n = 3
---
loopcount = 2
n = 3
---
loopcount = 2
n = 4
enter while loop
n = 8
---
loopcount = 3
n = 8
---
n = 9
n= 9 > 4
exit
 

Cerebus451

Golden Member
Nov 30, 2000
1,425
0
76
Actually, the sequence is:

n = 0 to start
loopcount = 1

First while loop, n = 0, n < 4, n is incremented to 1
n += 2 * loopcount, n = 3
Back to the while loop, n = 3, n < 4, n is incremented to 4
n += 2 * loopcount, n = 6
Back to the while loop, n = 6, n > 4, n is incremented to 7, break while loop

Next in for loop, loopcount is now 2
Into the while loop, n = 7, n > 4, n is incremented to 8, break while loop

Next in for loop, loopcount is now 3
Into the while loop, n = 8, n > 4, n is incremented to 9, break while loop

Next in for loop, loopcount is now 4, loopcount > 3, break for loop
Done.