Fibonacci Series In C# Console Application

In this blog we will create a program in c# for printing Fibonacci series to N level.

What is a Fibonacci Number?

A Fibonacci number is a series of numbers in which each Fibonacci number is obtained by adding the two preceding numbers. It means that the next number in the series is the addition of two previous numbers. Let the first two numbers in the series be taken as 0 and 1. By adding 0 and 1, we get the third number as 1. Then by adding the second and the third number (i.e) 1 and 1, we get the fourth number as 2, and similarly, the process goes on.
1. using System;
2. using System.Collections.Generic;
3. using System.Linq;
4. using System.Text;
6.
7. namespace FibonacciExample
8. {
9.     class Program
10.     {
11.         static void Main(string[] args)
12.         {
13.             Console.WriteLine("-----------------------------------------------------------");
14.             Console.WriteLine("---------------------Fibonacci Example--------------------");
15.             Console.WriteLine("-----------------------------------------------------------");
16.
17.             int num1 = 0, num2 = 1, num3, num4;
18.             Console.Write("Enter Number Of Element : ");
20.
21.             Console.WriteLine("Your Fibonacci Series Of "+num3+" Elements is below");
22.             Console.Write(num1 + " " + num2 + " ");
23.             for (int i = 2; i < num3; i++)
24.             {
25.                 num4 = num1 + num2;
26.                 Console.Write(num4 + " ");
27.                 num1 = num2;
28.                 num2 = num4;
29.             }
31.
32.         }
33.     }
34. }
Code Explanation
• Here first we declare four int variable num1, num2, num3, and num4 and assign num1 0 and num2 to 2.
• Then we print message for user.
• In the next line we get input from user and convert that number into integer.
• Then we print first two numbers which are 0 and one before loop.
• Next iterate loop from 2 to the number which user enters.  Why from two? Because above we print 0 and 1.
• In loop we assign num1 and num2 to num3 and print num3.
• Then we assign num2 to num1 and num3 to num3.
• Then we use the Console.ReadKey() method to read any key from the console. By entering this line of code, the program will wait and not exit immediately. The program will wait for the user to enter any key before finally exiting. If you don't include this statement in the code, the program will exit as soon as it is run.
OutPut