The Gateway to Computer Science Excellence

+21 votes

Consider the following C program:

void abc(char*s) { if(s[0]=='\0')return; abc(s+1); abc(s+1); printf("%c",s[0]); } main() { abc("123"); }

- What will be the output of the program?
- If $abc(s)$ is called with a null-terminated string $s$ of length $n$ characters (not counting the null ('\0') character), how many characters will be printed by $abc(s)$?

+30 votes

Best answer

Answer is **a)** $332 \ 332 \ 1$

Answer **b)** $2^n-1$

**Q**. **a) **$O/p$ :

**3 3 2 3 3 2 1**

**b)** : $T(n) = 2T(n-1) +1 ; n>0 $

$= 0 ; n=0$ [Since for length zero string no character will be printed]

After solving it by substitution,

$T(n) = 2T(n-1) +1$

$= 2(2T(n-2) + 1 ) +1$

$= 2^2T(n-2) + 2 +1$

$= 2^2(2T(n-3) +1 ) + 2 + 1$

$= 2^3T(n-3) + 2^2 + 2 + 1$

Finally, it will expand like

$= 2^nT(n-n) + 2^{n-1} + 2^{n-2} + \ldots + 2^2 + 2 + 1 $

$= 2^nT(0) + 2^{n-1} + 2^{n-2} + \ldots+ 2^2 + 2 + 1$

$= \frac{1.(2^n -1)}{(2 - 1)}$

$= 2^n -1$

0

0

how it can possible that we have problm of size n and after diving it into subprobem it size gets incresed . its not possible , but if u r willing to increase the size of problem in each call then problem will never end.

0

its not possible one other way of checking is that solve ur recurrence relation it is giving time complexity in negative which is contradiction

+1

https://gateoverflow.in/754/gate2001-13?show=145156#c145156

Refer this comment... Your doubts will get clarified..

+4 votes

ans for B is: 2^n -1

for length 2 -> 3 characters

for length 3-> 7 characters

for length 4-> 15 characters

hence for n-> 2^n - 1 characters

for length 2 -> 3 characters

for length 3-> 7 characters

for length 4-> 15 characters

hence for n-> 2^n - 1 characters

+5

**a) **3323321

**b) **we can also get the answer of b by solving recurrence relation

**T(n) = 2 * T(n-1) +1 ; n>0 **

** = 0 ; n=0** [Since for length zero string no character will be printed]

After solving it by substitution,

T(n) = 2 * T(n-1) +1

= 2 x (2 x T(n-2) + 1 ) +1

= 2^{2 }x T(n-2) + 2 +1

= 2^{2 }x (2*T(n-3) +1 ) + 2 + 1

= 2^{3 }x T(n-3) + 2^{2 }+ 2 + 1

Finally it will expand like

= 2^{n }x T(n-n) + 2^{n-1} + 2^{n-2} + - - - - - - - + 2^{2 }+ 2 + 1

= 2^{n }x T(0) + 2^{n-1 }+ 2^{n-2 }+ - - - - - - - - - - + 2^{2 }+ 2 + 1

= 1x (2^{n }-1) / (2 - 1 )

= 2^{n }-1

0

But how do we come to this recurrence relation first....i mean it works for all questions like this....do we have to learn this...please reply?

+4

lets assume to solve length n input it takes T(n) times

now in ques they have two abc(s+1) and one printf

abc(s+1) reduces the length of input by 1 so now it have length (n-1)

now to solve length (n-1) input it takes T(n-1) times and printf take 1 unit of time

hence reccurence relation is :

**T(n)=2.T(n-1)+1**

52,345 questions

60,517 answers

201,939 comments

95,368 users