Saturday, June 10, 2017

C# - Fibonacci Series

This post will show how we can print Fibonacci series using C# code.

Fibonacci Series:

a series of numbers in which each number ( Fibonacci number ) is the sum of the two preceding numbers. The simplest is the series 1, 1, 2, 3, 5, 8, etc.


class Program
    {
        static void Main(string[] args)
        {
            #region Fibonacci

            Console.WriteLine("Fibonacci series upto :");
            int num = int.Parse(Console.ReadLine());
            Console.WriteLine(PrintFibonacci(num));
            Console.ReadKey();

            #endregion
        }

#region Fibonacci

        private static string PrintFibonacci(int num)
        {
            int firstNumber = 0;
            int secondNumber = 1;
            int tempNumber = 1;
            string stringFibonacci = "\n" + firstNumber.ToString() + "\n" + secondNumber.ToString();

            for (int i = 0; i < num; i++)
            {
                tempNumber = firstNumber + secondNumber;
                firstNumber = secondNumber;
                secondNumber = tempNumber;
                stringFibonacci += "\n" + tempNumber.ToString();
            }
            return stringFibonacci;
        }

  #endregion

}

Console Output:

Fibonacci series upto :
10

0
1
1
2
3
5
8
13
21
34
55
89

No comments:

Post a Comment

SQL INTERVIEW QUESTIONS (SCENARIO BASED) - Part 1

FINDING Second Highest Salary in SQL CREATE TABLE #EMP ( NAME NVARCHAR ( 100 ), SALARY BIGINT ) INSERT INTO #EMP VALUES (...