+ 1

Array in c ?

Why can't able to get value and print the value in the same Loop int main(void){ int num; scanf("%d", &num); int fibonacci[num]; for (i = 2; i < num; i++){ finbonacci[i] = fibonacci[i - 2] + fibonacci[i - 2]; printf("%d", fibonacci[i]); } } It returns an unpredictable output

24th Dec 2020, 12:42 PM
T.K.SANTHOSH
T.K.SANTHOSH - avatar
2 Réponses
+ 4
There are many mistakes in your code 1. In the for loop declaration `for(i = 2; .....)`, you have not given the type of `i` 2. In the line, `finbonacci[i] = fibonacci[i - 2] + fibonacci[i - 2]`, note that you have written `finbonacci` instead of `fibonacci` After fixing these, your code will compile, but will give an undefined behaviour Try to visualize what happens in the loop 1st iteration: fibonacci[i] = fibonacci[i - 2] + fibonacci[i - 2] i = 2 fibonacci[2] = fibonacci[0] + fibonacci[0] Here your code is accessing fibonacci[0], which is uninitialized because you have not assigned a value to it. You will need to give the values for the 0th and 1th index of the fibonacci array, like so fibonacci[0] = 0; fibonacci[1] = 1; You code will now compile and give numbers that make sense, but will still not give the correct output. In the same line, fibonacci[i] = fibonacci[i - 2] + fibonacci[i - 2] you are adding `fibonacci[i - 2]`. Maybe you wanted one of them to be `fibonacci[i - 1]`?
24th Dec 2020, 1:09 PM
XXX
XXX - avatar
+ 1
/* Program to generate fibonacci number */ #include <stdio.h> int main(void) { int num, i; printf("Enter a number :"); scanf("%d", &num); int fib[num]; // Begins for (i = 0; i <= num; i++){ fib[i] = fib[i - 2] + fib[i - 1]; printf("%d\n", fib[i]); } } hey it's my code I just write the above with my mobile My mistake is I forgot to initialize 0 and 1 as 0 and 1 thank you so much
24th Dec 2020, 1:16 PM
T.K.SANTHOSH
T.K.SANTHOSH - avatar