Reputation: 1268
I'm trying to calculate the Fibonacci series in my c program but when i try to output the result, i get 4 weird sequences of numbers which i dont know what they mean.Are they memory addresses or what? What am i doing wrong?
#include <stdio.h>
void fibonacci(int N) {
if(N == 0) {
printf("0\n");
} else if(N == 1) {
printf("0\n1\n");
} else { // calculate the fibonacci number
int temp;
int i;
for (i = 0; i <= N; i++) {
temp += i;
printf("%d \n",temp);
}
}
return;
}
int main() {
int n;
do {
printf("Please insert a Natural Number: \n");
scanf("%d",&n);
} while (n < 0);
fibonacci(n);
return 0;
}
Upvotes: 0
Views: 305
Reputation: 2599
You are failing to initialise the temp
variable: you need
int temp = 0;
The reason is that automatic variables in C
have undefined values when they are declared. Automatic variables (variables declared inside functions are usually of this type) are allocated storage space in memory, but that storage space may well have been used for something else previously, in which case whatever value was last stored there will 'appear' in your variable. There is no way of knowing what this value will be. Make it a habit always to initialise variables when you declare them.
Upvotes: 2
Reputation: 26800
You have an uninitialized variable in your Fibonacci
function
int temp;
Access of uninitialized variable is undefined behaviour.
It is possible to create a variable without a value. This is very dangerous, but it can give an efficiency boost in certain situations. To create a variable without an initial value, simply don’t include an initial value:
// This creates an uninitialized int
int i;
The value in an uninitialized variable can be anything – it is unpredictable, and may be different every time the program is run. Reading the value of an uninitialized variable is undefined behaviour – which is always a bad idea. It has to be initialized with a value before you can use it.
Upvotes: 0