CS1010E TUTORIAL 11
Download
Report
Transcript CS1010E TUTORIAL 11
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
2* exponent(2, 2)
2* exponent(2, 1)
2* 2*2
Answer:
2* 2
8
2* exponent(2, 0)
2* 1
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);
if(k%2==0)
return y*y;
else
return (y*y*num);
}
}
// Function in 1(a)
Example
Let num=2;k=3
exponent2(2, 3)
exponent(2, 1)
y=2
exponent(2, 2)
y=4
k is odd
2* 2*2
Answer:
8
Let num=2;k=4
exponent2(2, 4)
k is even
4*4
Answer:
16
Question 2
int mul (int a,int b)
{
if (b==0)
return 0;
else
return (a + mul(a,b-1));
}
Example
Let a=2;b=3
2 + mul (2, 2)
2 + mul (2, 1)
2+2+2
Answer:
2+2
6
2 + mul (2, 0)
2