arrays - Fibonacci Sequence Error C -


i have assignment have write fibonacci's sequence , print first n numbers of it, n input user. wrote is:

#include <stdio.h> int main(int argc, char*argv[]){  int n, i, seq[n]; scanf("%d", &n); seq[0]=0; seq[1]=1; for(i=2; i<n; i++) seq[i]=seq[i-1]+seq[i-2];  for(i=0; i<n; i++) printf("%d ", seq[i]); return(0); } 

which works until n equal or bigger nine. supposing input 8, sequence 0 1 1 2 3 5 8 13 should be. if input 9 or bigger sequence looks 0 1 1 2 3 5 8 13 21 -9 (bunch of random numbers).

anyone can point out problem? thx in advance.

you declare int n, i, seq[n]; before have value of n set array's length with. behavior uninitialized variable undefined.

you don't need array assignment described. need remember last , current fibonacci values. sum them produce new one, migrate current -> last , new -> current. put logic in loop controlled n.


Comments

Popular posts from this blog

javascript - Slick Slider width recalculation -

jsf - PrimeFaces Datatable - What is f:facet actually doing? -

angular2 services - Angular 2 RC 4 Http post not firing -