Can that be done with no while loops?
static void Main(string[] args)
{
Console.WriteLine(\"Please enter a number\");
int number = Convert.ToInt32(C
That's a way to do it by returning a value into the main.
public static void Main() {
Console.WriteLine("Introduce the number");
int num = Convert.ToInt32(Console.ReadLine());
int num1 = 1, num2 = 1, counter = num-2;
//Take 2 out to match the list as first 2 numbers doesn't count in the function.
Console.WriteLine(Fibo(num1, num2, counter));
}
public static int Fibo(int num1, int num2, int counter) {
int temp = num1;
if (counter <= 0)
return num2;
else
return Fibo(num1 = num2, num2 += temp, counter-1);
}
I realize this may be an old thread, but oh well I think this kinda question is good in its nature.
Using while loop/or recursive way of doing is not the optimal way of doing as it takes a O(2^n) times. A better way to do this is using what is already in memory like below. This should take at most O(n) time.
Cheers!
static double fibDynamic(int n)
{
double[] array = new double[n];
array[0] = array[1] = 1;
for(int i = 2; i < n; i++)
{
array[i] = array[i - 1] + array[i - 2];
}
return array[n-1];
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
class Program
{
static int Main(string[] args)
{
int n, i = 0, c;
Console.WriteLine("Enter the number of terms:");
n = Convert.ToInt16(Console.ReadLine());
Console.WriteLine("Fibonacci series\n");
for (c = 1; c <= n; c++)
{
int result = FibonacciFunction(i);
Console.Write(result + " " );
i++;
}
Console.WriteLine();
return 0;
}
public static int FibonacciFunction(int n)
{
if (n == 0)
{
return 0;
}
else if (n == 1)
{
return 1;
}
else
{
return (FibonacciFunction(n - 1) + FibonacciFunction(n - 2));
}
}
}
}
public static int Fibonatchi(int position) {
if(position == 0) {
return 1;
}
if(position == 1) {
return 1;
} else {
return Fibonatchi(position - 2) + Fibonatchi(position - 1);
}
}
namespace Algorithms
{
class Program
{
static void Main(string[] args)
{
string fibResult = "";
fibResult = FibCal(10);
Console.WriteLine(fibResult);
Console.ReadLine();
}
public static string FibCal(int n)
{
string series = "";
int k, f1, f2 , f = 0;
f1 = f2 = 1;
if (n < 2)
return n.ToString();
else
for (k = 0; k < n; k++)
{
f = f1 + f2;
f2 = f1;
f1 = f;
series += f.ToString() + ",";
}
return series;
}
}
}
Hope this helps