Monday, July 27, 2009

Need an example of fibonacci and factorial in C# code?

Fibonacci:





public class Example


{


public static int Fibonacci(int n)


{


int previous = -1;


int result = 1;


for (int i = 0; i %26lt;= n; ++i)


{


int sum = result + previous;


previous = result;


result = sum;


}


return result;


}


}





For factorial use the same but instead of:





{


int sum = result + previous;


previous = result;


result = sum;


}





use





{


int fac = result * previous;


previous = result;


result = fac;


}

Need an example of fibonacci and factorial in C# code?
no idea..sorry
Reply:i am writing the program in C++ which is quite easy to change into C#








For Fibonacci numbers


!!





#include%26lt;iostream.h%26gt;


int fibonacci(int n)


{


if(n%26lt;1)


return 1;


else return(fibonacci(n-1)+fibonacci(n-2));


}


main()


{


int n;


int fibonacci;


cout%26lt;%26lt;"Enter the value if n where you need fibonacci(n)";


cin%26gt;%26gt;n;


fibonacci=fibonacci(n);


cout%26lt;%26lt;"Fibonacci("%26lt;%26lt;n%26lt;%26lt;")="%26lt;%26lt;fibonacci...


}





!!





For factorial


!!





#include%26lt;iostream.h%26gt;


int factorial(int n)


{


if(n%26lt;1)


return 1;


else return(factorial(n-1)*n)


}


main()


{


int n,factorial;


cout%26lt;%26lt;"Enter n";


cin%26gt;%26gt;n;


cout%26lt;%26lt;"Factorial of the number "%26lt;%26lt;n%26lt;%26lt;" is="%26lt;%26lt;factorial(n);


}





I think u can change this to C# easily.





I did it by recursion.





Think this serves your purpose


No comments:

Post a Comment