himanshu jhamb himanshu jhamb - 3 months ago 21
C Question

Why am i not able to print 47th fibonacci number correctly?

I am using 64 bit operating system ,then also i am not able to print 46th fibonacci number correctly which is less than 4 billion.

#include<cs50.h>
#include<stdio.h>

int main(void)
{

unsigned int n=50;
int array[n];
array[0]=0;
array[1]=1;
printf("%i\n",array[0]);
printf("%i\n",array[1]);
for(int i=2;i<n;i++)
{
array[i]=array[i-1]+array[i-2];
printf("%i\n",array[i]);
}

Answer

You have to use long long as your data type of the array. because You are going to store out-range numbers of the integer range.(-2,147,483,648 to 2,147,483,647) And declaration of int i should be before the for loop.

#include<stdio.h>

int main(void)
{

    int n=50;
    long long array[n];
    array[0]=0;
    array[1]=1;
    printf("%lli\n",array[0]);
    printf("%lli\n",array[1]);
    int i;
    for(i=2;i<n;i++)
    {
        array[i]=array[i-1]+array[i-2];
        printf("%lli\n",array[i]);
    }
}