in Operating System
1,693 views
1 vote
1 vote

main()

{

printf(" * ");

for(i=0;i<n;i++)

fork();

printf(" * ");

}

how many times * is printed??

in Operating System
1.7k views

1 Answer

2 votes
2 votes

2n  +1     

Try drawing a tree to understand how each fork works.

http://www.csl.mtu.edu/cs4411.ck/www/NOTES/process/fork/create.html

edited by

7 Comments

I am getting (2^n)+1 '*' only..

for eg for n 2

expanding the for loop (loop unrolling) it can be written as

(1) process (parent)-->

printf("*" );

fork();-----> creates new process (2) with code-----> fork(); printf("*")----->creates another (3)---->printf("*)

fork()------------> creates process (4) ----->printf("*);

printf("*);

So total * printed are 5 for n=2

In general for n for loops 2^n -1 child process would be created so 2^n-1 time * would be printed by child process + 2 times by parent ...in total 2^n+1 '*' would be printed.

0
0

Just review and let me know. the boxes represent an asterisk.horizontal bar is point where fork happens.

0
0
In the diagram for every black node (parent) you have printed '*' again and again. seems like you are considering printf inside for loop while its outside. I ran code on gcc compiler for n 3 it gives 10 "*" printed.
0
0
Oh yes ! I did misinterpreted bracket. But how did you get 10? It should be 9 then right?
1
1

 n for loops 2^n -1 child process would be created so 2^n-1 time * would be printed by child process + 2 times by parent ...in total 2^n+1 '*' would be printed.

Does it make clear...??

0
0
Yes I got it.But you said gcc gave you 10 as answer?
1
1
edited by

oh yes i didn't noticed it should be 9....:p

actually its giving different number of '*' everytime I execute.....

http://ideone.com/2hSoxN  ---> it now printed 16 *

and here https://code.hackerearth.com/7e4258A--->its 14
and I have no explanation for that.....may be its because printf buffers output and thus when child executes printf it gets displayed twice....

but i have no proper explanation for the behaviour....

0
0

Related questions