Sponsored Ad

Saturday, May 12, 2012

Interview Questions: How to Print 1 to 20 Numbers without using any loop in C#

One popular question in interview is that how to print a sequence with out using any loop. The simplest way is use the recursion to print the sequence. The below program is an example of this question. Which is using the recursion function to call and print the series.

Interview Questions: How to Print 1 to 20 Numbers without using any loop in C#

using System;

namespace ConsoleInterview
{
    class Programs
    {       
        static void Main(string[] args)
            {

                Console.WriteLine("Printing 1 to 20...");
                string strOutPut = "";
                PrintSequence(1, ref strOutPut);
                Console.WriteLine(strOutPut.Trim().TrimStart(','));               

                Console.ReadLine();
            }

        private static void PrintSequence(int Sequence, ref string FinalString)
        {
            if (Sequence <= 20)
            {
                FinalString += " ," + Sequence;
                Sequence += 1;              

                PrintSequence(Sequence, ref FinalString);
            }
        }
    }   
}

No comments:

Post a Comment

Sponsored Ad

Followers

Follow Us