- 1

Can someone explain this code

can someone explain how this code run per line thanks and please no negative comments CODE: public static string Fib(int n) { if(n<2) return "1"; int[ ] f = new int [n +1]; f[0] = 0; f[1] = 0; for (int i = 2; i <= n; i++) { f[ i ] = f[ i - 1] + f[ i - 2 ]; } return string.Join(" ",f); } OUTPUT: for example (int n = 5;) 0 1 1 2 3 5

30th Apr 2017, 8:38 AM
paupau oviedo
paupau oviedo - avatar
2 odpowiedzi
+ 5
It starts with f[0] and f[1] equal 0 and starts iterating over the list's items. The iteration builds an item by assigning it a value equal to the sum of the two previous ones. One exception - if n<2 it assigns 1. Then what is returned is a string built by .joining all the list items together, separated by a blank space. It's a standard code to produce the Fibonacci's sequence. EDIT: by list I mean an array :)
30th Apr 2017, 8:55 AM
Kuba Siekierzyński
Kuba Siekierzyński - avatar
0
the CODE contains some errors. corrected variant: public static string Fib(int n) { if(n<2) return "0"; int[] f = new int[n]; f[0] = 0; f[1] = 1; for (int i=2; i<n; i++) f[i]=f[i-1]+f[i-2]; return string.Join(" ",f); } for example, Console.WriteLine(Fib(6)); output: 0 1 1 2 3 5 Fib function creates new array, then first two elements of array is initialized by 0 and 1, other elements is calculated. The result is returned as a string.
30th Apr 2017, 6:15 PM
Андрей