Thursday, June 23, 2016

Sum of number Recursively and Fibonacci numbers recursively.

When you attend interview, people would ask you to write a program in visual that would sum the numbers from 10 and ask you to write a program that prints fibonacci numbers. So I thought I should put up something that is easy dirty and quick.

Sum of numbers is just one line or recursive code and fibonacci is fairly simple. These both programs uses recursive calls to calculate the sum or print numbers.  In the next blog I am going to write about FizzBuzz, Sorting numbers and Singleton class.


using System;
using System.Runtime.Remoting.Messaging;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Please enter a number");
            int inputVal = Convert.ToInt32(Console.ReadLine());
            Console.WriteLine(Sum(inputVal));

            Console.WriteLine("0");
            Console.WriteLine("1");
            PrintFibonacci(0, 1, inputVal);

            Console.ReadKey();

        }

        private static void PrintFibonacci(int first, int second, int inputVal)
        {
            if (inputVal < 3) return;
            int third = first + second;
            Console.WriteLine(third);
            PrintFibonacci(second,third,inputVal - 1);
        }


        static int Sum( int value)
        {
            return  (value == 0) ? 0 : value + Sum(value - 1);
        }
    }
}

No comments:

Post a Comment