This program is supposed to write 1 1 2 3 5 8 13 21 but it probably does not. Wh
ID: 3836459 • Letter: T
Question
This program is supposed to write 1 1 2 3 5 8 13 21 but it probably does not. What is the program doing that is incorrect? (We're not asking you explain why the incorrect action leads to the particular outcome it does, and we're not asking you to propose a fix to the problem.)
#include <iostream>
using namespace std;
int fibonacci( int n )
{
int tmp;
int a = 1;
int b = 1;
for (int i = 0; i < n-2; i ++)
{
tmp = a+b;
a = b;
b = tmp;
}
return b;
}
int* computeFibonacciSequence(int& n)
{
int arr[8];
n = 8;
for (int k = 0; k < n; k++)
{
arr[k] = fibonacci( k );
}
return arr;
}
int main()
{
int m;
int* ptr = computeFibonacciSequence(m);
for (int i = 0; i < m; i++)
{
cout << ptr[i] << ' ';
}
return( 0 );
}
Explanation / Answer
*In the above program we are not using pointers in the correct way to do the intended function
*In the function 'computeFibonacciSequence' the iput parameter should be 'int* n' not 'int& n' in order to store the address. And in the function code second line should be '*n=8' and in the for loop 'i<*n' should be there.
*In the main function while calling the 'computeFibonacciSequence' function we should pass '&m' as parameter instead of 'm'
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.