Ask your own question, for FREE!
Computer Science 15 Online
OpenStudy (anonymous):

this is a simple C code using nested loop #include #include int main() { int i,j; for(i=1;i<=3;i++) for (j=1; j<=3; j++) printf("i=%d\tj=%d\n",i,j); getchar (); return 0; } Can some one please explain why the value of "i" doesn't change till "j=3" every time?

OpenStudy (anonymous):

In nested loop the inner loop is executed first and then outer. I hope that's the answer! :) not very sure though!

OpenStudy (anonymous):

Its a nested loop...first i will get a value...lets say 1...then the next loop will be executed until j <= 3 that is twice...then again it will go back to the outer for loop..the process will go on

OpenStudy (e.mccormick):

Mandila, that is basically correct. The outer loop is executed first, however, it dos not iterate (loop) until what is inside it is finished. In this case, what is inside is another loop. So that code is executed next, and it has a print. So it does print, iterate, print, iterate, print, iterate, at limit which ends. This finishes the inner loop, then the outer loop iterates finally. In other words, the outer loop does technically execute first, but it iterates after the other one. However, if it is multiple choice answer and they do not mention the iteration, saying the inner loop executes first is an OK description of this process. That is because while the outer loop starts executing first, the inner loop finishes executing first.

OpenStudy (anonymous):

Let's see what happens here "step by step" : 1. i=1, i<=3 : condition true 2. control goes to inner loop. 3. j=1; j<=3: condition true, 4.printed value : 1=1 , j=1 5. j++ 6. NOTE: the value of i changes only when the condition of the inner loop fails. basically, that's the reason that the value of i doesn't changes till j=3. 7. now, j=2, j<=3 : cond true; 8. printed values : *i=1* , j=2 .. And the same continues...! :-)

OpenStudy (e.mccormick):

That's what I said.... just with pretty numbers and organization. =P

OpenStudy (anonymous):

Haha :D You see, numbers make things interesting to read ;) xD

OpenStudy (anonymous):

Thanks a lot everyone! this was my first question in open study and i'm quiet amazed how it worked that out! Thanks again for all your replies! Explanations were quiet sufficient! :D

Can't find your answer? Make a FREE account and ask your own questions, OR help others and earn volunteer hours!

Join our real-time social learning platform and learn together with your friends!
Can't find your answer? Make a FREE account and ask your own questions, OR help others and earn volunteer hours!

Join our real-time social learning platform and learn together with your friends!