Can that be done with no while loops?
static void Main(string[] args)
{
Console.WriteLine(\"Please enter a number\");
int number = Convert.ToInt32(C
Simple and easy solution :
static void Main(string[] args)
{
int number;
Console.WriteLine("enter number");
number = int.Parse(Console.ReadLine());
Console.WriteLine(Recursive(number));
Console.ReadLine();
}
public static int Recursive(int number)
{
if (number <= 2)
{
return 1;
}
else
{
return Recursive(number - 1) + Recursive(number - 2);
}
}
Using recursion in this fashion is a very bad idea. It will cause memory problems very quickly. I know you want to avoid using while/for loops, but an array is really the best way to go.
public static class Golden
{
public static IEnumerable<long> Fibonacci()
{
var a = 0L;
var b = 1L;
var s = 0L;
yield return a;
while (a < long.MaxValue - b)
{
yield return b;
s = a + b;
a = b;
b = s;
}
}
public static IEnumerable<long> FibonacciR()
{
IEnumerable<long> Fibo(long a, long b)
{
yield return a;
if (a < long.MaxValue - b)
{
foreach (var v in Fibo(b, a + b))
{
yield return v;
}
}
}
return Fibo(0, 1);
}
}
Using LINQ
public static void fibSeriesEx3()
{
List<int> lst = new List<int> { 0, 1 };
for (int i = 0; i <= 10; i++)
{
int num = lst.Skip(i).Sum();
lst.Add(num);
foreach (int number in lst)
Console.Write(number + " ");
Console.WriteLine();
}
}
static void Main(string[] args)
{
Console.WriteLine("Please enter a number");
int number = Convert.ToInt32(Console.ReadLine());
Fibonacci(0, 1, 1, number);
}
public static void Fibonacci(int a, int b, int counter, int number)
{
Console.WriteLine(a);
if (counter < number) Fibonacci(b, a+b, counter+1, number);
}
I didn't find a way to do it closest way is it to combine both loops + recursion
static void Main(string[] args)
{
Console.WriteLine("Please enter a number");
int number = Convert.ToInt32(Console.ReadLine());
for(int counter=0;counter<number;counter++)
Console.WriteLine(" \n" + Fibonacci(counter) );
}
public static int Fibonacci(int number)
{
if (number == 0)
return 0;
else if(number ==1)
return 1;
else
{
return Fibonacci(number - 2) + Fibonacci(number - 1);
}
}