Basic Recursion

I choose to print numbers 1 to 5 in this code.  When I step through it using F11 I get to the line
return stval;

Open in new window

It goes to the end of the routine, but does not go back to the calling command  
printNatural(1, ctr);

Open in new window

Instead it goes back to  this line of code
return printNatural(stval + 1, ctr);

Open in new window

several time before it goes back to the static main method.
Why does it not go straight back to static main after
return stval;

Open in new window


using System;

namespace ConsoleApp10
{

    class Program
    {
        static void Main(string[] args)
        {
            Console.Write("\n\n Recursion : Print the first n natural number :\n");
            Console.Write("---------------------------------------------------\n");
            Console.Write(" How many numbers to print : ");
            int ctr = Convert.ToInt32(Console.ReadLine());
            // Call recursive method with two parameters.	
            printNatural(1, ctr);
            Console.Write("\n\n");

        }
        static int printNatural(int stval, int ctr)
        {
            if (ctr < 1)
            {
                return stval;
            }
            ctr--;
            Console.Write(" {0} ", stval);
            return printNatural(stval + 1, ctr);
        }
    }
}

Open in new window

AlHal2Asked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

it_saigeDeveloperCommented:
Because your control variable has to be less than 1.  Until your control variable is less than one, your function will call itself (creating a new instance) over and over while deducting 1 from the control variable.  Each created instance get's placed on top of the call stack.  The first time you get to the line:
return stval;

Open in new window

You have 6 instances of your function on the stack:Capture.PNGAs each instance is popped from the stack, it's result is sent to the instance which initiated the call, the last instance is the only instance which will return to the main method call:Capture.PNGCapture.PNGUsing the call stack window you can see all of this happening.

-saige-

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
AlHal2Author Commented:
What would be a better implementation?
it_saigeDeveloperCommented:
Well in this instance, you want to simply print out numbers in sequence so a *better* implementation would do just that; e.g. -
using System;

namespace EE_Q29139617
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.Write("\n\n Looping : Print the first n natural number :\n");
            Console.Write("---------------------------------------------------\n");
            Console.Write(" How many numbers to print : ");
            int ctr = Convert.ToInt32(Console.ReadLine());
            // Call recursive method with two parameters.	
            printNatural(ctr);
            Console.Write("\n\n");
            Console.ReadLine();
        }

        static int printNatural(int ctr)
        {
            for (int i = 1; i < ctr + 1; i++)
            {
                Console.Write(" {0} ", i);
            }
            return 0;
        }
    }
}

Open in new window

Understand that this is not a recursive implementation.  It is a looping implementation.

-saige-
JavaScript Best Practices

Save hours in development time and avoid common mistakes by learning the best practices to use for JavaScript.

AlHal2Author Commented:
Thanks.
AndyAinscowFreelance programmer / ConsultantCommented:
If you want to learn about recursion then:
        static void Main(string[] args)
        {
            Console.Write("\n\n Recursion : Print the first n natural number :\n");
            Console.Write("---------------------------------------------------\n");
            Console.Write(" How many numbers to print : ");
            int ctr = Convert.ToInt32(Console.ReadLine());
            // Call recursive method with two parameters.	
            printNatural(ctr);
            Console.Write("\n\n");
            Console.Read();
        }
        static int printNatural(int ctr)
        {
            if (ctr < 1)
            {
                return ctr;
            }
            Console.Write(" {0} ", ctr);
            ctr--;
            return printNatural(ctr);
        }

Open in new window


which gives
SNAG-0033.bmp
AlHal2Author Commented:
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
C#

From novice to tech pro — start learning today.