AlHal2
asked on
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
Why does it not go straight back to static main after
return stval;
It goes to the end of the routine, but does not go back to the calling command
printNatural(1, ctr);
Instead it goes back to this line of code
return printNatural(stval + 1, ctr);
several time before it goes back to the static main method.Why does it not go straight back to static main after
return stval;
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);
}
}
}
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Well in this instance, you want to simply print out numbers in sequence so a *better* implementation would do just that; e.g. -
-saige-
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;
}
}
}
Understand that this is not a recursive implementation. It is a looping implementation.-saige-
ASKER
Thanks.
If you want to learn about recursion then:
which gives
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);
}
which gives
ASKER
Thanks Andy. The example I chose was https://www.w3resource.com/csharp-exercises/recursion/index.php
ASKER