Which loop will be executed first in a nested loop?


Which loop will be executed first in a nested loop?



I am facing problem in understanding the mechanism of the nested loop given below:


for(i=1; i<=rows; ++i)
{
for(j=1; j<=i; ++j)
{
printf("* ");
}
printf("n");
}



My question is when will be the printf("n"); executed? Before the nested loop?


printf("n");





and any reason for that thought?
– Sourav Ghosh
Jun 29 at 10:41





Did you try to step it through a debugger?
– Sourav Ghosh
Jun 29 at 10:42





You need to stop skipping your comp sci classes. If you wanna pass you gotta go to class. Possible duplicate of What is the difference between procedural programming and functional programming?
– jww
Jun 29 at 10:56






If you write 2 statements in your code, why should the first statement be skipped but executed after second? There is no random reordering or reverse execution of statements.
– Gerhardh
Jun 29 at 11:08





Why don't you just compile and run the code?
– klutt
Jun 29 at 12:36




5 Answers
5



No, the printf("n"); will be executed after the completion of the inner loop.


printf("n");



No, In each iteration of the outer loop, the inner loop will be executed. After inner loop is completed then it will execute printf("n"); statement.


printf("n");



printf("n") will execute when the execution of inner loop gets over. Since inner loop is executing again and again by outer loop so the printf("n") statement will execute after printing * i times.



Considering rows=5 and i and j as unsigned int (I mean, avoiding overflows and so on), the output will be:


rows=5


i


j


unsigned int


*
* *
* * *
* * * *
* * * * *



Edit: you only have to compile (gcc main.c -o test) your code and execute test:


gcc main.c -o test


#include<stdio.h>

int main()

{
unsigned int i;
unsigned int j;

for(i=1; i<=5; ++i) {
for(j=1; j<=i; ++j) {
printf("* ");
}
printf("n");
}
}



The printf("n"); will execute after the inner for-loop , for(j=1; j<=i; ++j). Exactly after printing '*' i times.


printf("n");


for-loop


for(j=1; j<=i; ++j)


*


i





So, will there be an extra newline after printing all the stars before showing the execution time and other things?
– Aditya Datta
Jun 29 at 11:36






@AdityaDatta yes. Was it missing when you tried to run the code?
– Gerhardh
Jun 29 at 11:38





No, It exists there
– Aditya Datta
Jun 29 at 11:39





@AdityaDatta There will be an extra newline (n).
– anoopknr
Jun 29 at 13:52


newline


n






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Comments

Popular posts from this blog

paramiko-expect timeout is happening after executing the command

how to run turtle graphics in Colaboratory

Export result set on Dbeaver to CSV