GATE / CS ARCHIVE

SIMILAR QUESTIONS / PROGRAMMING IN C

Expand doubled suffix recursion to output or print count

2 questions solved the same way, newest first. Back to Programming in C

How these are solved

The identical shared abc routine makes two calls on s+1 and prints s[0] after both. Expansion gives exact output for "123"; recurrence C(n)=2C(n-1)+1 gives count for general null-terminated length n.

Descriptive
Report issue

Trace doubled suffix recursion

Recursion

Question 13(a), GATE 2001: abc(s) returns at the null terminator; otherwise it calls abc(s+1) twice and then prints s[0]. main calls abc("123").
Question 13(a), GATE 2001: abc(s) returns at the null terminator; otherwise it calls abc(s+1) twice and then prints s[0]. main calls abc("123").
Tap to enlarge
Answer & solution

Answer: 3323321 (no official key was published)

Step through it (33 steps)

Let F(s) be the string printed by a call. F(empty)=empty and F(cs)=F(s)F(s)c. Therefore F("3")="3", F("23")="3"+"3"+"2"="332", and F("123")="332"+"332"+"1"="3323321". The recursive calls finish before the current character is printed, so the initial character appears last. No spaces or newline are printed.

Original paper, page 9

Descriptive
Report issue

Count recursion output characters

Recursion

Question 13(b), GATE 2001: The preceding abc routine is called on a null-terminated string of n characters, excluding the terminator.
Question 13(b), GATE 2001: The preceding abc routine is called on a null-terminated string of n characters, excluding the terminator.
Tap to enlarge
Answer & solution

Answer: 2^n − 1 characters (no official key was published)

For n=0 the function immediately returns and prints zero characters. For n>0 it makes two calls on length n−1 and prints one character itself. Thus C(0)=0 and C(n)=2C(n−1)+1. Expanding gives C(n)=1+2+4+…+2n−1=2n−1. Equivalently, induction substitutes C(n−1)=2n−1−1 to get 2n−1. The null-terminator calls contribute no output. For n=3 this predicts seven characters, agreeing with 3323321.

Original paper, page 9