In: Computer Science
Q2:
The following code is supposed to return the sum of the numbers between 1 and n inclusive, for positive n. An analysis of the code using our "Three Question" approach reveals that:
int sum(int n){
if (n == 1)
return 1;
else
return (n + sum(n - 1));
}
Answer Choices:
it passes on all three questions and is a valid algorithm.
it fails the smaller-caller question.
it fails the base-case question.
it fails the general-case question.
Q3:
What does the following return, when passed the argument 1564?
int recur(int n)
{
if (n < 0) return -1;
else
if (n < 10) return n;
else
return ((n % 10) + recur(n / 10));
}
Answer Choices:
160
16
-1
4
Q4:
The following code is supposed to return n!, for positive n. An analysis of the code using our "Three Question" approach reveals that:
int factorial(int n){
if (n == 0)
return 2;
else
return (n * factorial(n – 1));
}
Answer Choices:
it fails the base-case question.
it fails the general-case question.
it passes on all three questions and is a valid algorithm.
it fails the smaller-caller question.
Q2.
Ans: (a) it passes on all three questions and is a valid algorithm.
Because it satisfies all case.
Q3.
Ans: 16
It adds all the digits of the number.
Q4.
Ans: (a) it fails the base-case question.
Here base case is 0!=1 and 1!=1
But these condtions are not correct in program . so base case fails.
Here base case fails . so entire program is wrong it does not satisfy any case.