UNIVERSITY OF THE PUNJAB
Fourth Semester 2017
Examination: B.S. 4 Years Programme
Paper: Data Structure and Algorithm
Course Code: IT-207 / IT-22408
Short Questions
b) What is the output of the following code
#include<iostream>
using namespace std;
int fun1(int n){
if(n==1)
return 0;
else
return 1 + fun1(n/2);
}
int main(){
cout<<"answer is = "<<fun1(32)<<endl;
return 0;
}
Solution:
fun1(32)
↓ return 1 + fun1(16);
↓ return 1+ fun1(8);
↓ return 1+ fun1(4);
↓ return 1+ fun1(2);
↓ return 1+ fun1(1);
return 0;
↑ return 1 + 0;
↑ return 1+ 1;
↑ return 1+ 2;
↑ return 1 + 3;
↑ return 1 + 4;
return 5;
Ans: answer is = 5
↓ return 1 + fun1(16);
↓ return 1+ fun1(8);
↓ return 1+ fun1(4);
↓ return 1+ fun1(2);
↓ return 1+ fun1(1);
return 0;
↑ return 1 + 0;
↑ return 1+ 1;
↑ return 1+ 2;
↑ return 1 + 3;
↑ return 1 + 4;
return 5;
Ans: answer is = 5
Let me know in the comment section if you have any question.
Previous Post:
Write down the Postfix notation of the following expression: 9 - 3 + 2 * ( 3 * 4 - 3 ) / 4 + 2 * 1 | PU | Past Paper 2017
Comments
Post a Comment