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:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
namespace PrintValues | |
{ | |
class PrintTest | |
{ | |
static void Main(string[] args) | |
{ | |
Console.WriteLine("Please enter from and to numbers\n"); | |
string[] numbers = Console.ReadLine().Split(); | |
int fromNumber = int.Parse(numbers[0]); | |
int toNumber = int.Parse(numbers[1]); | |
PrintTest objPrintTest = new PrintTest(); | |
Console.WriteLine("\nList of numbers with Recursion"); | |
Console.WriteLine("----------------"); | |
objPrintTest.PrintWithRecursion(fromNumber, toNumber); | |
Console.WriteLine("\n\nList of numbers with goto"); | |
Console.WriteLine("----------------"); | |
objPrintTest.PrintWithGoto(fromNumber, toNumber); | |
Console.Read(); | |
} | |
//printing the numbers using recursion | |
void PrintWithRecursion(int fromNumber, int toNumber) | |
{ | |
if (fromNumber <= toNumber) | |
{ | |
Console.Write(fromNumber + " "); | |
fromNumber++; | |
PrintWithRecursion(fromNumber, toNumber); | |
} | |
} | |
//Printing the numbers using goto statement. | |
void PrintWithGoto(int fromNumber, int toNumber) | |
{ | |
Repeat: | |
if (fromNumber <= toNumber) | |
{ | |
Console.Write(fromNumber + " "); | |
fromNumber++; | |
goto Repeat; | |
} | |
Console.Read(); | |
} | |
} | |
} |
output: