Access over 35 million academic & study documents

5 Consider the following function and main program driver void f

Content type
User Generated
Rating
Showing Page:
1/3
5. Consider the following function and main program
driver:
void f(int n){
int a=0;
int b=1;
while (a < n){
cout<<a<<endl;
a=b;
b=a+b;
}
};
int main(){
for(int i=1; i<50;i++){
cout<<\"i= \"<<i<<endl;
f(i);
cout<<endl;
}
system(\"PAUSE\");
return 0;
}
Write a recursive function to do the same thing.
Solution
#include<iostream>
#include<cassert>
using namespace std;
// utility function

Sign up to view the full document!

lock_open Sign Up
Showing Page:
2/3
void fUtil(int a, int b, int n){
if(a >= n)
return ;
else{
cout<<a<<endl;
fUtil(b, a+b, n); // recursive call
}
}
void f(int n){
// passing initial parameters to utility function
fUtil(0, 1, n);
};
int main(){
for(int i=1; i<50;i++){
cout<<\"i= \"<<i<<endl;
f(i);
cout<<endl;
}
system(\"PAUSE\");
return 0;
}

Sign up to view the full document!

lock_open Sign Up
Showing Page:
3/3

Sign up to view the full document!

lock_open Sign Up
Unformatted Attachment Preview
5. Consider the following function and main program driver: void f(int n){ int a=0; int b=1; while (a < n){ cout ...
Purchase document to see full attachment
User generated content is uploaded by users for the purposes of learning and should be used following Studypool's honor code & terms of service.

Anonymous
Really useful study material!

Studypool
4.7
Indeed
4.5
Sitejabber
4.4