Data Structure Multiple Choice Questions on “Length of a String using Recursion”.
1. Consider the following iterative implementation to find the length of the string:
#includeint get_len(char *s) { int len = 0; while(________) len++; return len; } int main() { char *s = "harsh"; int len = get_len(s); printf("%d",len); return 0; }
Which of the following lines should be inserted to complete the above code? Answer: c 2. What is the output of the following code? a) 14 Answer: a 3. What is the time complexity of the following code used to find the length of the string? a) O(1) Answer: b 4. What is the output of the following code? a) 0 5. Which of the following can be the base case for the recursive implementation used to find the length of a string? a) if(string[len] == 1) return 1 Answer: c 6. Consider the following recursive implementation used to find the length of a string: Which of the following lines should be inserted to complete the above code? Answer: d 7. What is the output of the following code? a) 5 Answer: b 8. What is the time complexity of the following recursive implementation used to find the length of the string? a) O(1) 9. How many times is the function recursive_get_len() called when the following code is executed? a) 6 10. What is the output of the following code? a) 3
a) s[len-1] != 0
b) s[len+1] != 0
c) s[len] != ‘ ’
d) s[len] == ‘ ’
Clarification: The line “s[len] != ‘ ′” should be inserted to complete the above code.#include
b) 0
c) Compile time error
d) Runtime error
Clarification: The program prints the length of the string “lengthofstring”, which is 14.#include
b) O(n)
c) O(n2)
d) O(logn)
Clarification: The time complexity of the code used to find the length of the string is O(n).#include
b) 1
c) Runtime error
d) Garbage value
Answer: a
Clarification: The program prints the length of an empty string, which is 0.#include
b) if(string[len+1] == 1) return 1
c) if(string[len] == ‘ ’) return 0
d) if(string[len] == ‘ ’) return 1
Clarification: “if(string[len] == ‘ ’) return 0” can be used as base case in the recursive implementation used to find the length of the string.#include
a) 1
b) len
c) recursive_get_len(s, len+1)
d) 1 + recursive_get_len(s, len+1)
Clarification: The line “1 + recursive_get_len(s, len+1)” should be inserted to complete the code.#include
b) 6
c) 7
d) 8
Clarification: The above code prints the length of the string “abcdef”, which is 6.#include
b) O(n)
c) O(n2)
d) O(n3)
Answer: b
Clarification: The time complexity of the above recursive implementation used to find the length of the string is O(n).#include
b) 7
c) 8
d) 9
Answer: c
Clarification: The function recursive_get_len() is called 8 times when the above code is executed.#include
b) 6
c) 9
d) 10
Answer: c
Clarification: The above program prints the length of the string “123-1-2-3”, which is 9.