The Fibonacci sequence is a sequence where the next number is the sum of the previous two numbers. The first two numbers of fibonacci series are 0 and 1.
C# Fibonacci Series up to n terms
private static void Main(string[] args)
{
int i, num, num1 = 0, num2 = 1;
int nextNum = num1 + num2;
Console.WriteLine("Enter the number of terms: ");
num = int.Parse(Console.ReadLine());
Console.Write("Fibonacci Series: {0}, {1}, ", num1, num2);
// print 3rd to nth terms
for (i = 3; i <= num; ++i)
{
Console.Write("{0}, ", nextNum);
num1 = num2;
num2 = nextNum;
nextNum = num1 + num2;
}
Console.ReadLine();
}
Output:
C# Fibonacci Series Up to nth Number
private static void Main(string[] args)
{
int num, num1 = 0, num2 = 1;
int nextNum = num1 + num2;
Console.WriteLine("Enter the number: ");
num = int.Parse(Console.ReadLine());
Console.Write("Fibonacci Series: {0}, {1}, ", num1, num2);
while (nextNum <= num)
{
Console.Write("{0}, ", nextNum);
num1 = num2;
num2 = nextNum;
nextNum = num1 + num2;
}
Console.ReadLine();
}
Output: