I am trying to print numbers from 1 to 100 without using loops, using C#. Any clues?
Recursion maybe?
public static void PrintNext(i) {
if (i <= 100) {
Console.Write(i + " ");
PrintNext(i + 1);
}
}
public static void Main() {
PrintNext(1);
}
Console.Out.WriteLine('1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100');
Method A:
Console.WriteLine('1');
Console.WriteLine('print 2');
Console.WriteLine('print 3');
...
Console.WriteLine('print 100');
Method B:
func x (int j)
{
Console.WriteLine(j);
if (j < 100)
x (j+1);
}
x(1);
Enumerable.Range(1, 100)
.Select(i => i.ToString())
.ToList()
.ForEach(s => Console.WriteLine(s));
Not sure if this counts as the loop is kind of hidden, but if it's legit it's an idiomatic solution to the problem. Otherwise you can do this.
int count = 1;
top:
if (count > 100) { goto bottom; }
Console.WriteLine(count++);
goto top;
bottom:
Of course, this is effectively what a loop will be translated to anyway but it's certainly frowned upon these days to write code like this.
Just for the ugly literal interpretation:
Console.WriteLine("numbers from 1 to 100 without using loops, ");
(you can laugh now or later, or not)
namespace ConsoleApplication2 {
class Program {
static void Main(string[] args) {
Print(Enumerable.Range(1, 100).ToList(), 0);
Console.ReadKey();
}
public static void Print(List<int> numbers, int currentPosition) {
Console.WriteLine(numbers[currentPosition]);
if (currentPosition < numbers.Count - 1) {
Print(numbers, currentPosition + 1);
}
}
}
}