Translate this function into an iterative version:
Here is my solution:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
int f(int i)
{
int prev,next,final;
prev = 0;
next = 1;
if(n==1)
final = i; //Correct- 1 mark
}
for(int i = 0; i <= n;i++) //Wrong
{
final = prev + next;
prev = next; //Correct- 1 mark
next = final; //Correct- 1 mark
return final;
}
Can someone help me figure out why my if statement was wrong and help me find a reduced or different solution?
int f(int i)
{
int prev,next,final;
prev = 0;
next = 1;
if(n==1) //What is n? Where did that came from?
final = i;
} //dunction ends here. Everything down from here does not belong to it
for(int i = 0; i <= n;i++) //you are using n again (and you should start with 2)
{
final = prev + next;
prev = next;
next = final;
return final; //Uncinditional return. Your loopo will iterate only once before returning.
}
DId you test your code? It doesn't even compile, end even if it did it does not work properly. Simple test would show you all that.
#include<iostream>
usingnamespace std;
int f(int i)
{
int prev,next,final;
prev = 0;
next = 1;
if(i==1)
final = i; //Correct- 1 mark
for(int i = 2; i <= final;i++) //Wrong
{
final = prev + next;
prev = next; //Correct- 1 mark
next = final; //Correct- 1 mark
}
return final;
}
int main()
{
int ans = f(5);
cout << ans << endl;
return 0;
}