-1

"I am writing code for fibonacci series and after 44th term in series, i start getting negative values in series Why?

#include <stdio.h>
int main(void)
{
  int i, n , t1 = 0 ,t2 = 1 ,next;
  printf("Enter the number of terms for series:");
  scanf("%d", &n);
  while(i<=n){
    next = t1 +t2 ;
    t1 = t2;
    t2 = next;
    printf("%d\n", next);
    i++;
  }
  return 0;
}

" expected output is fibonacci series upto any number of term but after 44th term I start getting negative values in series"

Achal
  • 11,821
  • 2
  • 15
  • 37
  • 1
    Any good book should have explained things like the numeric ranges. If your book doesn't cover that, then I really suggest you find a better book. – Some programmer dude May 25 '19 at 10:48

2 Answers2

2

You get negative values cause the 45th element of the fibonacci series is over the max value that can be reached by an integer. (2 147 483 647)

lfalkau
  • 896
  • 7
  • 21
0

I did not test the program, but I think I know the answer.

The numbers tend to get very big very fast. 44 is already a big number. (e.g. you can use the debugger to see what is going on.)

It is very likely that "int" is not big enough to hold the number, so then some unexpected things happen.

Try modifying your program to use 64-bit variables ("long long"). Things will change. Even "unsigned int" will give you some extra room, but not much.


Additional hints:

  1. Use a "for" instead of a "while", since that is your actual intention.
  2. It is good practice to initialize variables before using them. "i" and "next" are used before they are initialized.
virolino
  • 2,073
  • 5
  • 21