(a) Non-recursive function
void funct_iter(unsigned n){
unsigned prev0 = 1, prev1 = 2;
for (unsigned i = 1; i <= n; i++){
if (i == 1 || i == 2) cout << i << " ";
else {
unsigned temp = prev1;
prev1 = (prev0 + prev1) * 2;
prev0 = temp;
cout << prev1 << " ";
}
}
cout << endl;
}
(b) Recursion
unsigned funct_rec0(unsigned n){
if (n == 0 || n == 1) return n + 1;
else return (funct_rec0(n - 1) + funct_rec0(n - 2)) * 2;
}
void funct_rec1(unsigned cur, unsigned n){
if (cur <= n){
cout << funct_rec0(cur - 1) << " ";
funct_rec1(cur + 1, n);
}
else cout << endl;
}
void funct_rec(unsigned n){
funct_rec1(1, n);
}
Execution (main function):
int main() {
funct_rec(6);
funct_iter(6);
return 0;
}
Output:
1 2 6 16 44 120
1 2 6 16 44 120
Comments
Leave a comment