rahul
rahul

Reputation: 289

How to print 1 to 100 without any looping using C#

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

Upvotes: 22

Views: 42949

Answers (28)

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(x);
x+=1;
...
x+=1
Console.WriteLine(x);

Upvotes: 12

Sonal
Sonal

Reputation: 31

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);
            }
}

Upvotes: 0

LucidCoder
LucidCoder

Reputation: 1

    [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; }
    }

Upvotes: 0

Awesomni.Codes
Awesomni.Codes

Reputation: 2428

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();
    }

Upvotes: 0

Donnie
Donnie

Reputation: 46933

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');

Upvotes: 66

sujeet pasi
sujeet pasi

Reputation: 11

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();
    }
}

Upvotes: 1

J&#246;rg W Mittag
J&#246;rg W Mittag

Reputation: 369546

using static IronRuby.Ruby;

class Print1To100WithoutLoopsDemo
{
    static void Main() => 
      CreateEngine().Execute("(1..100).each {|i| System::Console.write_line i }");
}

Hey, why not?

Upvotes: 14

Todd Richardson
Todd Richardson

Reputation: 1129

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

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

public void print(int x, int limit)
{
    Console.WriteLine(++x);
    if(x != limit)
        print(x, limit);
}

Upvotes: 8

Abdulsattar Mohammed
Abdulsattar Mohammed

Reputation: 10742

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.

Upvotes: 0

Wayne Conrad
Wayne Conrad

Reputation: 108089

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

Upvotes: 7

Shay Ben-Moshe
Shay Ben-Moshe

Reputation: 1296

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) { }
}

Upvotes: 1

David R Tribble
David R Tribble

Reputation: 12204

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

Upvotes: 0

Matthew Whited
Matthew Whited

Reputation: 22443

Just LINQ it...

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

Upvotes: 5

Kevin
Kevin

Reputation: 8561

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);

Upvotes: 2

Mark Schultheiss
Mark Schultheiss

Reputation: 34196

Just for the ugly literal interpretation:

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

(you can laugh now or later, or not)

Upvotes: 8

Juliet
Juliet

Reputation: 81526

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();
        }
    }
}

Upvotes: 9

Pavel Minaev
Pavel Minaev

Reputation: 101615

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)))); }
}

Upvotes: 199

brendan
brendan

Reputation: 29996

public void Main()
{
  printNumber(1);
}

private void printNumber(int x)
{
  Console.WriteLine(x.ToString());
  if(x<101)
  {
    x+=1;
    printNumber(x);
  }
}

Upvotes: 1

dso
dso

Reputation: 9580

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.

Upvotes: 8

Faisal Abid
Faisal Abid

Reputation: 9140

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);       
}

Upvotes: 0

Mark Carpenter
Mark Carpenter

Reputation: 17775

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);
            }
        }
    }
}

Upvotes: 0

Jo&#227;o Angelo
Jo&#227;o Angelo

Reputation: 57718

One more:

Console.WriteLine(
   String.Join(
      ", ", 
      Array.ConvertAll<int, string>(
         Enumerable.Range(1, 100).ToArray(), 
         i => i.ToString()
      )
   )
);

Upvotes: 46

jason
jason

Reputation: 241701

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.

Upvotes: 12

Raj
Raj

Reputation: 1770

PrintNum(1);
private void PrintNum(int i)
{
   Console.WriteLine("{0}", i);
   if(i < 100)
   {
      PrintNum(i+1);
   } 
}

Upvotes: 0

Caleb
Caleb

Reputation: 9468

Recursion maybe?

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

public static void Main() {
    PrintNext(1);
}

Upvotes: 60

wallyk
wallyk

Reputation: 57784

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);

Upvotes: 5

Jack
Jack

Reputation: 133609

I can think two ways:

  • using 100 Console.WriteLine
  • using goto in a switch statement

Upvotes: 2

ojrac
ojrac

Reputation: 13421

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.

Upvotes: 7

Related Questions