Sunday, August 2, 2009

Fibonacci sequence in C# using for loops??

I want to display 1st 20 numbers in sequence but don't have a clue please help.

Fibonacci sequence in C# using for loops??
The syntax here will not be right, but this approach will work








F[1] = 0


F[2] = 1





For N = 1 to 20 do


If (N %26lt;%26gt; 1) %26amp;%26amp; (N%26lt;%26gt;2) Then


F[N] = F[N-1] + F[N-2]


Endif


Print "Fib " N " = " F[N]


End For
Reply:int number1;


int number2;


number1=number2=1;


Console.WriteLine("{0}", number1);


while (number2 %26lt; 20)


{


Console.WriteLine(number2);


number2 += number1;


number1 = number2 - number1; Report It

Reply:Hi,


I don't know how to program in C# but I did write a similar program in java. The syntax is the same. I will explain it and just show you the function method I used, because I am not sure what you are using to display the results.





Basically in your constructor you want to have a loop which will run 20 times, run a function method to calculate the fibonacci number and then display such result. This is what it may look like:


for(i=1;i%26lt;=20;++i)


{


display.writeString("The "+i+"th Fibonacci number is "+Fib(i)); // this will pass the value of i to the method and display that result


display.writeEOL(); // End of line


}





Your function method might look something like this:


private int Fib(int n){


if(n%26lt;=1){


return n;


}





else{


return Fib(n-2)+Fib(n-1);





}


}





I would try to help more but I have never programmed in C#. Hopefully you can translate this information :). To be honest I had trouble at first and had to look at source codes done in C.
Reply:I do not know what C# means.


if(n ==0 ) return 0


if(n == 1) return 1


if (n %26gt; 1) return (f(n-1)+f(n-2))


Ignore 'return.'


The above is the formula to generate the sequence.


Here are the the first 21 numbers.


The first number is 0. The seond is 1. Each number is the sum of the 2 previous numbers.


0


1


1


2


3


5


8


13


21


34


55


89


144


233


377


610


987


1597


2584


4181


6765


No comments:

Post a Comment