In some interviews we may get a question like print certain numbers without using any loops.
There are many approaches to accomplish this task. Here i am giving two of the approaches
1) With recursion
2) With goto statement.
With Recursion
void PrintWithRecursion(int fromNumber, int toNumber)
{
if (fromNumber <= toNumber)
{
Console.Write(fromNumber + " ");
fromNumber++;
PrintWithRecursion(fromNumber, toNumber);
}
}
With goto statement
void PrintWithGoto(int fromNumber, int toNumber)
{
Repeat:
if (fromNumber <= toNumber)
{
Console.Write(fromNumber + " ");
fromNumber++;
goto Repeat;
}
Console.Read();
}
Complete Source code:
1) With recursion
2) With goto statement.
With Recursion
void PrintWithRecursion(int fromNumber, int toNumber)
{
if (fromNumber <= toNumber)
{
Console.Write(fromNumber + " ");
fromNumber++;
PrintWithRecursion(fromNumber, toNumber);
}
}
With goto statement
void PrintWithGoto(int fromNumber, int toNumber)
{
Repeat:
if (fromNumber <= toNumber)
{
Console.Write(fromNumber + " ");
fromNumber++;
goto Repeat;
}
Console.Read();
}
Complete Source code:
output:
No comments:
Post a Comment