70 likes | 227 Views
CS1010E TUTORIAL 11. RECURSION P SANDEEP A13. Question 1(a). int exponent ( int num, int k) { //Base condition if(k==0) return 1; //Recursive condition else return ( num * exponent(num,k-1) ); }. Example. Let num=2;k=3 Answer:.
E N D
CS1010E TUTORIAL 11 RECURSION P SANDEEP A13
Question 1(a) • int exponent (int num, int k) { //Base condition if(k==0) return 1; //Recursive condition else return ( num * exponent(num,k-1) ); }
Example • Let num=2;k=3 • Answer: 2* exponent(2, 2) 2* exponent(2, 1) 2* exponent(2, 0) 2* 2*2 2* 2 2* 1 8
Question 1(b) double exponent2 (int num, int k) { //Base condition double y; if(k==0) return 1; //Recursive condition else { y=exponent(num, k/2); // Function in 1(a) if(k%2==0) return y*y; else return (y*y*num); } }
Example • Let num=2;k=3 • k is odd • Answer: • Let num=2;k=4 • k is even • Answer: exponent2(2, 3) exponent(2, 1) y=2 2* 2*2 8 exponent2(2, 4) exponent(2, 2) y=4 4*4 16
Question 2 • intmul (inta,int b) • { • if (b==0) • return 0; • else • return (a + mul(a,b-1)); • }
Example • Let a=2;b=3 • Answer: 2 + mul (2, 2) 2 + mul (2, 1) 2 + mul (2, 0) 2+2+2 2+2 2 6