1,720 views
2 2 votes
For following code how many times the '*' will printed?

main()

{

     int i,n ;

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

     {

         fork();

         printf("*");

     }

}

3 Answers

3 3 votes

For each $fork()$ function call, the parent creates one child. So, there are $2$ child nodes for each fork call (i.e. one parent + one child). The above example creates a complete binary tree, where each level from $1$ to $n$ describes a total number of children after a $fork()$ system call. After, $n$ level, the tree is left with one parent + $(n-1)$ child, each of which executes the printf(“*”). For each iteration of the for loop, the print(“*”) will be executed.

$\therefore$ total number of $* =$ (total number of nodes possible for tree with n+1 height) – 1

$=(2^{n+1}-1) – 1$

$=2^{n+1}-2$

ex- for n=2, total number of * will be $2^3-2=6$

edited by
0 0 votes
Since there is a `printf("*");` statement inside the loop and the loop will run `n` times, each process will print '*' `n` times.

For every iteration of the loop, the number of processes doubles because both the parent and child processes will fork again in the next iteration. So,

the total number of '*' printed by all processes combined will be `2^n`, where `n` is the value of `n` in the loop condition.
edited by
Position:
Show:

Related questions

1 1 vote
1 1 answer
1.1k
1.1k views
Athul 1 asked Dec 31, 2024
1,077 views
2. Consider a process P that executes the fork system call twice. That is, it runs code like this: int ret1 = fork(); int ret2 = fork(); How many direct children of P (i....
3 3 votes
1 1 answer
658
658 views
Athul 1 asked Dec 30, 2024
658 views
8. Consider a simple linux shell implementing the command sleep 100. Which of the following is an accurate ordered list of system calls invoked by the shell from the time...
2 2 votes
1 1 answer
1.2k
1.2k views
abhiagr2 asked Oct 19, 2024
1,226 views
fork(); fork(); printf("Gate2024"); fork();what will be the answer?
0 0 votes
4 4 answers
2.1k
2.1k views
vivek1211 asked Jul 5, 2023
2,050 views
#include <stdio.h>void main(){ int i = 3; while(i>0) { i ; if(fork()||fork()) { printf("Hi"); } }}How many times “Hi” w...