tried to take terms in array and printed that array but expected output is different from my output not able to find the logic behind it.
code:-
#include <iostream>
using namespace std;
int main() {
int num;
int t1=0;
int t2=1;
int next;
cin>>num;
int arr[num];
for (int i = num-1; i >= 0; i--)
{
if (i == num-t1-1)
{
arr[i] = t1;
continue;
}
if (i == num-t2-1)
{
arr[i] = t2;
continue;
}
next = t1+t2;
arr[i] = next;
t1 = t2;
t2 = next;
}
for(int j=0;j<num;j++)
{
cout<<arr[j]<<" ";
}
return 0;
}
what is wrong in this code? output if user enter 20 is
one additional 8 is coming in between 21 and 13.
Your code is a good example of how code should not be written.:)
It is very difficult to understand your code. It's a rule that badly readable code is bound to contain bugs.
For example there are used three variables t1
, t2
and next
to assign values to elements of the array
arr[i] = t1;
//...
arr[i] = t2;
//...
arr[i] = next;
and it is not clear for which value of the variable i
there will be used one of the assignments.
For starters variable length arrays like this
int arr[num];
are not a standard C++ feature. Instead you should use standard container std::vector
.
That is if you write a C++ program you should use features provided by the C++ language.
Your code is invalid. For example when i
is equal to 11
then t1
is equal tp 8
. and this if statement
if (i == num-t1-1)
in this case is equivalent to
if ( 11 == 20-8-1)
or
if ( 11 == 11 )
and the value of t1
is written in the array element arr[11]
. instead of writing the value 21
.
Here is a demonstration program that shows how your assignment can be performed.
#include <iostream>
#include <functional>
#include <vector>
#include <iterator>
int main()
{
unsigned int n;
if (std::cin >> n && n != 0)
{
std::vector<unsigned long long> v( n );
std::pair<unsigned long long, unsigned long long> fibonacci( 0, 1 );
for (auto first = std::rbegin( v ), last = std::rend( v ); first != last; ++first)
{
*first = fibonacci.first;
fibonacci.first =
std::exchange( fibonacci.second, fibonacci.first + fibonacci.second );
}
for (const auto &item : v)
{
std::cout << item << ' ';
}
std::cout << '\n';
}
}
The program output is the same as expected.
20
4181 2584 1597 987 610 377 233 144 89 55 34 21 13 8 5 3 2 1 1 0
Pay attention that instead of using the signed type int
for the variable num
you should use an unsigned integer type as for example unsigned int
. And to avoid an overflow the variables t1
and t2
should have at least the type unsigned long long int
.
In the provided demonstration program this declaration
std::pair<unsigned long long, unsigned long long> fibonacci( 0, 1 );
makes it clear that the program deals with fibonacci numbers.