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.
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
-
- namespace FibonacciExample
- {
- class Program
- {
- static void Main(string[] args)
- {
- Console.WriteLine("-----------------------------------------------------------");
- Console.WriteLine("---------------------Fibonacci Example--------------------");
- Console.WriteLine("-----------------------------------------------------------");
-
- int num1 = 0, num2 = 1, num3, num4;
- Console.Write("Enter Number Of Element : ");
- num3 = Convert.ToInt32(Console.ReadLine());
-
- Console.WriteLine("Your Fibonacci Series Of "+num3+" Elements is below");
- Console.Write(num1 + " " + num2 + " ");
- for (int i = 2; i < num3; i++)
- {
- num4 = num1 + num2;
- Console.Write(num4 + " ");
- num1 = num2;
- num2 = num4;
- }
- Console.ReadKey();
-
- }
- }
- }
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