CcoderBeginner
CcoderBeginner

Reputation: 101

My array displays 50 elements then i get random memory sizes, why is that?

If i try to input the 50th number in the series it displays until the 46th and then generates random numbers however when i counted the characters in both i found they were both equal to 10, so why does it stop at precisely 46?

My Code:

void calculating_f(int val){
    int aray[100] = {0,1};
    int i;

    printf("%i %i ", aray[0], aray[1]);
    for (i=2; i < val; i++){
      aray[i] = aray[i - 2] + aray[i - 1];
      printf("%i ", aray[i]);
    }
}

Upvotes: 0

Views: 78

Answers (3)

cm161
cm161

Reputation: 510

[Answer after correction]
Thanks to @mch for pointing out the mistake in my answer about using 'unsigned int data type'.

Please use 'unsigned long long int (64bit data type)' and '%llu' format specifier for printf() call.

[Answer before correction]
aray is storing int data as per definition.

When you are giving limit val = 50, then, the calculated value is exceeding the max value of signed integer data type when i = 47.

You should change data type to 'unsigned int' and use '%u' in format specifier in printf() call.

Upvotes: 0

hassan arafat
hassan arafat

Reputation: 667

it's because you're using int, int in c can hold numbers from –2,147,483,648 to 2,147,483,647, but the 47th Fibonacci number is 2971215073 which is outside that range causing an overflow.you could try using a long long which will get you up to the 92nd Fibonacci number.

p.s if you only want to get the n-th Fibonacci number there's no need for the array. look into Matrix exponentiation if you need to calculate the n-th Fibonacci number, it's much faster than what you're doing if you only need the n-th Fibonnaci number

Upvotes: -1

keithmo
keithmo

Reputation: 4943

Integer overflow (assuming ints are 32-bits on your system). The 46th Fibonacci number is largest that will fit into a signed 32-bit value.

BTW -- You don't really need an array for this.

Upvotes: 2

Related Questions