views:

3236

answers:

23

I am trying to print numbers from 1 to 100 without using loops, using C#. Any clues?

+12  A: 
Console.WriteLine('1');
Console.WriteLine('2');
...
Console.WriteLine('100');

...Or would you have accepted a recursive solution?

EDIT: or you could do this and use a variable:

int x = 1;
Console.WriteLine(x);
x+=1;
Console.WriteLine('2');
x+=1;
...
x+=1
Console.WriteLine('100');
FrustratedWithFormsDesigner
+1 for the recursive idea. Even though it's a bit abusive of the stack, it would work and it's only an assignment, presumably.
JMD
I haven't done C# in awhile, but couldn't you just just do Console.WriteLine( ++x ); instead of doing x += 1 before each line? (Obviously initializing the variable beforehand.
William
You could even use the variable the other 99 times! ;-)
Jim Ferrans
@Jim: yes, I'm a bit TOO quick with the copy/paste.I also had an idea to use events: Increase x, raise an event whose listener prints the event arg (which contains x).I see the recursive solution was the selected answer. I had hoped someone would submit a lambda solution. ;)
FrustratedWithFormsDesigner
+5  A: 

I can think of two ways. One of them involves about 100 lines of code!

There's another way to reuse a bit of code several times without using a while/for loop...

Hint: Make a function that prints the numbers from 1 to N. It should be easy to make it work for N = 1. Then think about how to make it work for N = 2.

ojrac
+48  A: 

Console.Out.WriteLine('1,2,3,4, ... ,100');

Donnie
I vote for this one :D
Sudhir Jonathan
definitely the right answer
Stefano Borini
I'm sorry, this only prints 5 numbers, not all 100.
Adam Woś
I hope that Adam was joking in his comment. Of course it only prints 5 numbers. It's just shorthand.
Allain Lalonde
+1  A: 

I can think two ways:

  • using 100 Console.WriteLine
  • using goto in a switch statement
Jack
+4  A: 

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);
wallyk
I really don't want to downvote on such a silly question, but he did say using c#. :)
Donnie
@Donnie, this *seems* to be a homework question, which means users are encouraged to not give the exact code, but rather enough of a push in the right direction for the OP to figure it out, which I think @wallyk has done quite well. +1
Brandon
@Brandon, fair enough. And I didn't downvote either, was just saying :)
Donnie
+36  A: 

Recursion maybe?

public static void PrintNext(i) {
    if (i <= 100) {
        Console.Write(i + " ");
        PrintNext(i + 1);
    }
}

public static void Main() {
    PrintNext(1);
}
Caleb
Gratuitous "but first you have to understand recursion" comment.
Greg Beech
Isnt this a loop?
Leroy Jenkins
Recursion generally isn't considered a loop, even though its behaving similar to a loop.
Kyle Trauberman
Guess I need to read about Recursion. +1 for the help, thank you.
Leroy Jenkins
Although strictly not a loop, it's still using an incremental counter and a limit, so it's a clumsy loop ;)
Cecil Has a Name
A loop generally implies a mutable counter, this one doesn't have that (every invocation has its own "counter").
Pavel Minaev
@Cecil: I don't think Noam Chomsky would think that
0A0D
Recursion is more general than a loop.
trinithis
Couldn't you have simply called Main() recursively?
NTDLS
The easiest way to learn recursion is to learn recursion.
Chris
+13  A: 
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.

Jason
Both samples contain a loop.
Henk Holterman
+1 for the goto! :)
FrustratedWithFormsDesigner
A: 
public void Main()
{
  printNumber(1);
}

private void printNumber(int x)
{
  Console.WriteLine(x.ToString());
  if(x<101)
  {
    x+=1;
    printNumber(x);
  }
}
brendan
LOl posted a similar answer 8 seconds after you :(
Faisal Abid
shouldn't x be incremented? :DStackoverflow!
Jack
doh! fixed now :-)
brendan
A: 

This is more or less pseudo code I havent done c# in years, PS running on 1 hour of 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);       
}
Faisal Abid
You want `return;` instead of `break;` in your edge case. And `print()` isn't the correct function -- presumably you want `Console.WriteLine()`.
Daniel Pryden
A: 
PrintNum(1);
private void PrintNum(int i)
{
   Console.WriteLine("{0}", i);
   if(i < 100)
   {
      PrintNum(i+1);
   } 
}
Raj
+39  A: 

One more:

Console.WriteLine(
   String.Join(
      ", ", 
      Array.ConvertAll<int, string>(
         Enumerable.Range(1, 100).ToArray(), 
         i => i.ToString()
      )
   )
);
João Angelo
`String.Join` is a nice solution, indeed! How didn't it come to my mind immediately?
fviktor
Brilliant answer.
Allain Lalonde
String.Join, Array.ConvertAll, Enumerable.Range and ToArray all use for/foreach constructs. You can't just encapsulate them and claim there is no looping!
Callum Rogers
@Callum, there are no loop constructs in my C# code as requested. :) This answer is all about plausible deniability and how to make the printed output look prettier using `String.Join`.
João Angelo
+8  A: 
Enumerable.Range(1, 100).ToList().ForEach(i => Console.WriteLine(i));

Here's a breakdown of what is happening in the above code:

Performance Consideration

The ToList call will cause memory to be allocated for all items (in the above example 100 ints). This means O(N) space complexity. If this is a concern in your app i.e. if the range of integers can be very high, then you should avoid ToList and enumerate the items directly.

Unfortunately ForEach is not part of the IEnumerable extensions provided out of the box (hence the need to convert to List in the above example). Fortunately 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 IEnumerable extension in place, now in all the places where you need to apply an action to an IEnumerable you can simply call ForEach with a lambda. So now the original example looks like this:

Enumerable.Range(1, 100).ForEach(i => Console.WriteLine(i));

The only difference is that we no longer call ToList, and this results in constant (O(1)) space usage... which would be a quite noticeable gain if you were processing a really large number of items.

DSO
Yea, but there's a loop in there!
0A0D
A: 
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);
            }
        }
    }
}
Pwninstein
+4  A: 

By the time I answer this, someone will already have it, so here it is anyway:

void Main()
{
    print(0, 100);
}

public void print(int x, int limit)
{
    Console.WriteLine(++x);
    if(x != limit)
        print(x, limit);
}
fauxtrot
Credit to Caleb.
fauxtrot
+12  A: 
using IronRuby;

class Print1To100WithoutLoopsDemo
{
    static void Main()
    {
        Ruby.CreateEngine().Execute("(1..100).each {|i| puts i}");
    }
}

Hey, why not?

Jörg W Mittag
Great approach!
fauxtrot
The answer to all C# questions.
Robert Fraser
+132  A: 

No loops, no conditionals, and no hardcoded literal output, aka "divide and conquer 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)))); }
}
Pavel Minaev
Clever. Evil, but clever.
Jonathan Allen
This is truly brilliant!
FrustratedWithFormsDesigner
This is innovative, but I see it as valuable as writing down 100 `WriteLine` statements :)
Gregory Pakosz
+1 Have never seen this. Very smart!
Viet
This is the job security answer - brilliant
Mike Robinson
Clever, but then the next question will be how to print 1 to 101. How do you handle prime numbers?
Ozan
@Ozan: 1 to 101 is { P64(); P32(); P4(); P1(); }, 1 to 7 is { P4(); P2(); P1(); }.
Rasmus Faber
I love the power of two ladder approach for this. Very clever. I also like the lambda recursion model. But you should make your answer complete by also showing a self-attenuating closure.
LBushkin
@LBushkin: you can really think of the power of two ladder as or-ing together bit flags. 100 = 0b1100100, 64 = 0b1000000, 32 = 0b0100000, and 4 = 0b0000100, so 64 | 32 | 4 = 100. Coolness!
Juliet
@LBushkin: I'm not sure what you mean by "self-attenuating closure"; can you clarify (or maybe just post it as a separate answer)?
Pavel Minaev
I wish I could favourite answers.
Matt Grande
Truly wonderful feeling seeing this answer...
Umair Ahmed
How the hell did this come to your mind? :) Simply superb!
Dienekes
+6  A: 

No loops, no recursion, just a hashtable-like 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();
        }
    }
}
Juliet
A: 

well... you could do it with extreme goto usage .. something like

function print100()
{
  int i =0;
  0: 
    print(++i)
    goto i;
  1:
  2:
  3:
  4:
  ..
  ..
  ..
  98:
  99:goto 0;
  100:return;
}
Gaby
C# requires the destination of a `goto` to be a valid identifier (can't use 1:) or a constant expression (can't use `goto i`).
Iceman
`goto` is the most basic form of a loop.
Atømix
+4  A: 

With regular expressions in a shell script calling gnu sed. Someone who knows C# can make the trivial conversion.

#!/bin/sh

# Count to 127 in unary
echo '' >numbers
echo 'x' >>numbers
cat numbers >temp ; sed -r -e 's/(x*)$/\1xx/g' temp >>numbers
cat numbers >temp ; sed -r -e 's/(x*)$/\1xxxx/g' temp >>numbers
cat numbers >temp ; sed -r -e 's/(x*)$/\1xxxxxxxx/g' temp >>numbers
cat numbers >temp ; sed -r -e 's/(x*)$/\1xxxxxxxxxxxxxxxx/g' temp >>numbers
cat numbers >temp ; sed -r -e 's/(x*)$/\1xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx/g' temp >>numbers
cat numbers >temp ; sed -r -e 's/(x*)$/\1xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx/g' temp >>numbers

# Out of 0..127, select 1..100
sed -i -r -n -e '2,101p' numbers

# Convert from unary to decimal

sed -i -r -e 's/x{10}/<10>/g' numbers
sed -i -r -e 's/x{9}/<9>/g' numbers
sed -i -r -e 's/x{8}/<8>/g' numbers
sed -i -r -e 's/x{7}/<7>/g' numbers
sed -i -r -e 's/x{6}/<6>/g' numbers
sed -i -r -e 's/x{5}/<5>/g' numbers
sed -i -r -e 's/x{4}/<4>/g' numbers
sed -i -r -e 's/x{3}/<3>/g' numbers
sed -i -r -e 's/x{2}/<2>/g' numbers
sed -i -r -e 's/x{1}/<1>/g' numbers
sed -i -r -e 's/(<10>){10}/<100>/g' numbers
sed -i -r -e 's/(<10>){9}/<90>/g' numbers
sed -i -r -e 's/(<10>){8}/<80>/g' numbers
sed -i -r -e 's/(<10>){7}/<70>/g' numbers
sed -i -r -e 's/(<10>){6}/<60>/g' numbers
sed -i -r -e 's/(<10>){5}/<50>/g' numbers
sed -i -r -e 's/(<10>){4}/<40>/g' numbers
sed -i -r -e 's/(<10>){3}/<30>/g' numbers
sed -i -r -e 's/(<10>){2}/<20>/g' numbers
sed -i -r -e 's/(<[0-9]{3}>)$/\1<00>/g' numbers
sed -i -r -e 's/(<[0-9]{2}>)$/\1<0>/g' numbers
sed -i -r -e 's/<([0-9])0*>/\1/g' numbers

# Print 'em
cat numbers

# => 1
# => 2
# ...
# => 99
# => 100
Wayne Conrad
Oh... my... god....
Callum Rogers
By which I guess you mean: "I'd give you as many +1's as the system would allow, but I'm sort of busy hammering a pencil into my brain with Knuth vol. 1. Thanks a lot."
Wayne Conrad
Who's the sick puppy who voted this up? Fess up!
Wayne Conrad
+4  A: 

Just for the ugly literal interpretation:

Console.WriteLine("numbers from 1 to 100 without using loops, ");

(you can laugh now or later, or not)

Mark Schultheiss
+2  A: 

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);
Iceman
+3  A: 

Just LINQ it...

Console.WriteLine(Enumerable.Range(1, 100)
                            .Select(s => s.ToString())
                            .Aggregate((x, y) => x + "," + y));
Matthew Whited
A: 

My solution is in thread 2045637, which asks the same question for Java.

Loadmaster