0

I solving the problem of fibonacci series in c.It was going well.When I give input n=48 it show negative number. First 47 numbers shows correct answers.After n=47, it is showing error...what is bug in the code? I set 0 and 1 as first two default numbers of the series.

#include <stdio.h>

                                            //Find Fibonaaci Numbers .......
int main(){

    int s1,s2,c,n;
    s1=0;
    s2=1;
    c=3;
    printf("Enter a number ");
    scanf("%d",&n);
    printf("1. %d \n",s1);
    printf("2. %d \n",s2);

    for(c=3;c<=n;c++){


        s2=s1+s2;
        printf("%d. %d \n",c,s2);
        s1=s2-s1;
    }

}
Craig Estey
  • 30,627
  • 4
  • 24
  • 48
Noman
  • 11
  • 1
  • What is the 48th number in the series? Is is `2971215073`. What value is `INT_MAX`? It is (32-bit) `2147483647`. Which is larger? – Weather Vane Jul 05 '22 at 17:02
  • @Noman At least use unsigned long long int instead of int. – Vlad from Moscow Jul 05 '22 at 17:05
  • Your choice of an int for s1 and s2 results in wrap around when the computed Fibonacci number exceeds INT_MAX. – Jim Rogers Jul 05 '22 at 17:19
  • @Noman If you haven't learned it already, learn it now: The variables we use in computer programs are not ideal. Type `int` implements a *subset* of the integers; it cannot represent arbitrary integers. It can represent integers only in some fixed range, typically -32768 to 32767 (on older 16-bit machines), or -2147483648 to 2147483647 if you're on a 32-bit machine. – Steve Summit Jul 05 '22 at 17:55
  • **Never say “I got an error” without telling us what the error is.** Cut & paste the exact error so that we can see what it says. If we can't see the error, we can't tell what the problem is. It's like taking your car to the mechanic and saying "The car makes a noise" but not telling what the noise is. – Andy Lester Jul 05 '22 at 18:08
  • @AndyLester You misunderstood. The OP wrote "I give input n=48 it show negative number. First 47 numbers shows correct answers.After n=47, it is showing error" meaning the output value was in error (not that there was a specific error message from the compiler or runtime). – Steve Summit Jul 05 '22 at 18:56

0 Answers0