[ACCEPTED]-How to print 1 to 100 without any looping using C#-recursion
No loops, no conditionals, and no hardcoded 2 literal output, aka "divide and conquer 1 FTW" solution:
class P
{
static int n;
static void P1() { System.Console.WriteLine(++n); }
static void P2() { P1(); P1(); }
static void P4() { P2(); P2(); }
static void P8() { P4(); P4(); }
static void P16() { P8(); P8(); }
static void P32() { P16(); P16(); }
static void P64() { P32(); P32(); }
static void Main() { P64(); P32(); P4(); }
}
Alternative approach:
using System;
class C
{
static int n;
static void P() { Console.WriteLine(++n); }
static void X2(Action a) { a(); a(); }
static void X5(Action a) { X2(a); X2(a); a(); }
static void Main() { X2(() => X5(() => X2(() => X5(P)))); }
}
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');
0
Recursion maybe?
public static void PrintNext(i) {
if (i <= 100) {
Console.Write(i + " ");
PrintNext(i + 1);
}
}
public static void Main() {
PrintNext(1);
}
0
One more:
Console.WriteLine(
String.Join(
", ",
Array.ConvertAll<int, string>(
Enumerable.Range(1, 100).ToArray(),
i => i.ToString()
)
)
);
0
using static IronRuby.Ruby;
class Print1To100WithoutLoopsDemo
{
static void Main() =>
CreateEngine().Execute("(1..100).each {|i| System::Console.write_line i }");
}
Hey, why not?
0
Console.WriteLine('1');
Console.WriteLine('2');
...
Console.WriteLine('100');
...Or would you have accepted a recursive 2 solution?
EDIT: or you could do this and 1 use a variable:
int x = 1;
Console.WriteLine(x);
x+=1;
Console.WriteLine('2');
x+=1;
...
x+=1
Console.WriteLine('100');
Enumerable.Range(1, 100)
.Select(i => i.ToString())
.ToList()
.ForEach(s => Console.WriteLine(s));
Not sure if this counts as the loop is kind 6 of hidden, but if it's legit it's an idiomatic 5 solution to the problem. Otherwise you can 4 do this.
int count = 1;
top:
if (count > 100) { goto bottom; }
Console.WriteLine(count++);
goto top;
bottom:
Of course, this is effectively what 3 a loop will be translated to anyway but 2 it's certainly frowned upon these days to 1 write code like this.
No loops, no recursion, just a hashtable-like 1 array of functions to choose how to branch:
using System;
using System.Collections.Generic;
namespace Juliet
{
class PrintStateMachine
{
int state;
int max;
Action<Action>[] actions;
public PrintStateMachine(int max)
{
this.state = 0;
this.max = max;
this.actions = new Action<Action>[] { IncrPrint, Stop };
}
void IncrPrint(Action next)
{
Console.WriteLine(++state);
next();
}
void Stop(Action next) { }
public void Start()
{
Action<Action> action = actions[Math.Sign(state - max) + 1];
action(Start);
}
}
class Program
{
static void Main(string[] args)
{
PrintStateMachine printer = new PrintStateMachine(100);
printer.Start();
Console.ReadLine();
}
}
}
Enumerable.Range(1, 100).ToList().ForEach(i => Console.WriteLine(i));
Here's a breakdown of what is happening 21 in the above code:
- Enumerable.Range returns the specified range of integral numbers as IEnumerator<Int32>
- Enumerable.ToList<T> converts an IEnumerable<T> into a List<T>
- List<T>.ForEach takes a lamdba function and invokes it for each item in the list
Performance Consideration
The ToList call will cause 20 memory to be allocated for all items (in 19 the above example 100 ints). This means 18 O(N) space complexity. If this is a concern 17 in your app i.e. if the range of integers 16 can be very high, then you should avoid 15 ToList and enumerate the items directly.
Unfortunately 14 ForEach is not part of the IEnumerable extensions 13 provided out of the box (hence the need 12 to convert to List in the above example). Fortunately 11 this is fairly easy to create:
static class EnumerableExtensions
{
public static void ForEach<T>(this IEnumerable<T> items, Action<T> func)
{
foreach (T item in items)
{
func(item);
}
}
}
With the above 10 IEnumerable extension in place, now in all 9 the places where you need to apply an action 8 to an IEnumerable you can simply call ForEach 7 with a lambda. So now the original example 6 looks like this:
Enumerable.Range(1, 100).ForEach(i => Console.WriteLine(i));
The only difference is that 5 we no longer call ToList, and this results 4 in constant (O(1)) space usage... which 3 would be a quite noticeable gain if you 2 were processing a really large number of 1 items.
By the time I answer this, someone will 2 already have it, so here it is anyway, with 1 credit to Caleb:
void Main()
{
print(0, 100);
}
public void print(int x, int limit)
{
Console.WriteLine(++x);
if(x != limit)
print(x, limit);
}
Just for the ugly literal interpretation:
Console.WriteLine("numbers from 1 to 100 without using loops, ");
(you 1 can laugh now or later, or not)
I can think of two ways. One of them involves 7 about 100 lines of code!
There's another 6 way to reuse a bit of code several times 5 without using a while/for loop...
Hint: Make 4 a function that prints the numbers from 3 1 to N. It should be easy to make it work 2 for N = 1. Then think about how to make 1 it work for N = 2.
With regular expressions
using System.Text.RegularExpressions;
public class Hello1
{
public static void Main()
{
// Count to 128 in unary
string numbers = "x\n";
numbers += Regex.Replace(numbers, "x+\n", "x$&");
numbers += Regex.Replace(numbers, "x+\n", "xx$&");
numbers += Regex.Replace(numbers, "x+\n", "xxxx$&");
numbers += Regex.Replace(numbers, "x+\n", "xxxxxxxx$&");
numbers += Regex.Replace(numbers, "x+\n", "xxxxxxxxxxxxxxxx$&");
numbers += Regex.Replace(numbers, "x+\n", "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx$&");
numbers += Regex.Replace(numbers, "x+\n", "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx$&");
// Out of 1..128, select 1..100
numbers = Regex.Match(numbers, "(.*\n){100}").Value;
// Convert from unary to decimal
numbers = Regex.Replace(numbers, "x{10}", "<10>");
numbers = Regex.Replace(numbers, "x{9}", "<9>");
numbers = Regex.Replace(numbers, "x{8}", "<8>");
numbers = Regex.Replace(numbers, "x{7}", "<7>");
numbers = Regex.Replace(numbers, "x{6}", "<6>");
numbers = Regex.Replace(numbers, "x{5}", "<5>");
numbers = Regex.Replace(numbers, "x{4}", "<4>");
numbers = Regex.Replace(numbers, "x{3}", "<3>");
numbers = Regex.Replace(numbers, "x{2}", "<2>");
numbers = Regex.Replace(numbers, "x{1}", "<1>");
numbers = Regex.Replace(numbers, "(<10>){10}", "<100>");
numbers = Regex.Replace(numbers, "(<10>){9}", "<90>");
numbers = Regex.Replace(numbers, "(<10>){8}", "<80>");
numbers = Regex.Replace(numbers, "(<10>){7}", "<70>");
numbers = Regex.Replace(numbers, "(<10>){6}", "<60>");
numbers = Regex.Replace(numbers, "(<10>){5}", "<50>");
numbers = Regex.Replace(numbers, "(<10>){4}", "<40>");
numbers = Regex.Replace(numbers, "(<10>){3}", "<30>");
numbers = Regex.Replace(numbers, "(<10>){2}", "<20>");
numbers = Regex.Replace(numbers, "(<[0-9]{3}>)$", "$1<00>");
numbers = Regex.Replace(numbers, "(<[0-9]{2}>)$", "$1<0>");
numbers = Regex.Replace(numbers, "<([0-9]0)>\n", "$1\n");
numbers = Regex.Replace(numbers, "<([0-9])0*>", "$1");
System.Console.WriteLine(numbers);
}
}
The output:
# => 1
# => 2
# ...
# => 99
# => 100
0
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);
0
Just LINQ it...
Console.WriteLine(Enumerable.Range(1, 100)
.Select(s => s.ToString())
.Aggregate((x, y) => x + "," + y));
0
I can think two ways:
- using 100
Console.WriteLine
- using
goto
in aswitch
statement
0
A completely unnecessary method:
int i = 1;
System.Timers.Timer t = new System.Timers.Timer(1);
t.Elapsed += new ElapsedEventHandler(
(sender, e) => { if (i > 100) t.Enabled = false; else Console.WriteLine(i++); });
t.Enabled = true;
Thread.Sleep(110);
0
public void Main()
{
printNumber(1);
}
private void printNumber(int x)
{
Console.WriteLine(x.ToString());
if(x<101)
{
x+=1;
printNumber(x);
}
}
0
The cool and funny way:
static void F(int[] array, int n)
{
Console.WriteLine(array[n] = n);
F(array, n + 1);
}
static void Main(string[] args)
{
try { F(new int[101], 1); }
catch (Exception e) { }
}
0
class Program
{
static int temp = 0;
public static int a()
{
temp = temp + 1;
if (temp == 100)
{
Console.WriteLine(temp);
return 0;
}
else
Console.WriteLine(temp);
Program.a();
return 0;
}
public static void Main()
{
Program.a();
Console.ReadLine();
}
}
0
This is more or less pseudo code I havent 2 done c# in years, PS running on 1 hour of 1 sleep so i might be wrong.
int i = 0;
public void printNum(j){
if(j > 100){
break;
} else {
print(j);
printNum(j + 1);
}
}
public void main(){
print(i);
printNum(i + 1);
}
PrintNum(1);
private void PrintNum(int i)
{
Console.WriteLine("{0}", i);
if(i < 100)
{
PrintNum(i+1);
}
}
0
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);
}
}
}
}
0
class Program
{
static Timer s = new Timer();
static int i = 0;
static void Main(string[] args)
{
s.Elapsed += Restart;
s.Start();
Console.ReadLine();
}
static void Restart(object sender, ElapsedEventArgs e)
{
s.Dispose();
if (i < 100)
{
Console.WriteLine(++i);
s = new Timer(1);
s.Elapsed += Restart;
s.Start();
}
}
}
You must notice that I'm NOT using recursion.
0
Feeling a bit naughty posting this:
private static void Main()
{
AppDomain.CurrentDomain.FirstChanceException += (s, e) =>
{
var frames = new StackTrace().GetFrames();
Console.Write($"{frames.Length - 2} ");
var frame = frames[101];
};
throw new Exception();
}
0
[Test]
public void PrintNumbersNoLoopOrRecursionTest()
{
var numberContext = new NumberContext(100);
numberContext.OnNumberChange += OnNumberChange(numberContext);
numberContext.CurrentNumber = 1;
}
OnNumberChangeHandler OnNumberChange(NumberContext numberContext)
{
return (o, args) =>
{
if (args.Counter > numberContext.LastNumber)
return;
Console.WriteLine(numberContext.CurrentNumber);
args.Counter += 1;
numberContext.CurrentNumber = args.Counter;
};
}
public delegate void OnNumberChangeHandler(object source, OnNumberChangeEventArgs e);
public class NumberContext
{
public NumberContext(int lastNumber)
{
LastNumber = lastNumber;
}
public event OnNumberChangeHandler OnNumberChange;
private int currentNumber;
public int CurrentNumber
{
get { return currentNumber; }
set {
currentNumber = value;
OnNumberChange(this, new OnNumberChangeEventArgs(value));
}
}
public int LastNumber { get; set; }
public class OnNumberChangeEventArgs : EventArgs
{
public OnNumberChangeEventArgs(int counter)
{
Counter = counter;
}
public int Counter { get; set; }
}
0
static void Main(string[] args)
{
print(0);
}
public static void print(int i)
{
if (i >= 0 && i<=10)
{
i = i + 1;
Console.WriteLine(i + " ");
print(i);
}
}
0
More Related questions
We use cookies to improve the performance of the site. By staying on our site, you agree to the terms of use of cookies.