Print 1 to 1000 without loops or conditions

Task: print numbers from 1 to 1000 without using any loops or conditional statements. Don't write only 1000 printf() or cout statements.

How would you do this in C or C + +?

#1 building

Compile time recursion! P

#include <iostream>
template<int N>
struct NumberGeneration{
  static void out(std::ostream& os)
  {
    NumberGeneration<N-1>::out(os);
    os << N << std::endl;
  }
};
template<>
struct NumberGeneration<1>{
  static void out(std::ostream& os)
  {
    os << 1 << std::endl;
  }
};
int main(){
   NumberGeneration<1000>::out(std::cout);
}

#2 building

printf("%d\n", 2);
printf("%d\n", 3);

It doesn't print all the numbers, but it prints "print numbers from 1 to 1000.". Win the ambiguous question! )

#3 building

Here are three solutions I know. The second could be controversial.

// compile time recursion
template<int N> void f1()
{ 
    f1<N-1>(); 
    cout << N << '\n'; 
}

template<> void f1<1>() 
{ 
    cout << 1 << '\n'; 
}

// short circuiting (not a conditional statement)
void f2(int N)
{ 
    N && (f2(N-1), cout << N << '\n');
}

// constructors!
struct A {
    A() {
        static int N = 1;
        cout << N++ << '\n';
    }
};

int main()
{
    f1<1000>();
    f2(1000);
    delete[] new A[1000]; // (3)
    A data[1000]; // (4) added by Martin York
}

[edit: (1) and (4) can only be used for compile time constants, (2) and (3) can also be used for runtime expression end edits. ]

#4 building

#include <cstdlib>
#include <iostream>
#include <string>
using namespace std;

class Printer
{
public:
 Printer() { cout << ++i_ << "\n"; }
private:
 static unsigned i_;
};

unsigned Printer::i_ = 0;

int main()
{
 Printer p[1000];
}

#5 building

Untested but should be vanilla standard C:

void yesprint(int i);
void noprint(int i);

typedef void(*fnPtr)(int);
fnPtr dispatch[] = { noprint, yesprint };

void yesprint(int i) {
    printf("%d\n", i);
    dispatch[i < 1000](i + 1);
}

void noprint(int i) { /* do nothing. */ }

int main() {
    yesprint(1);
}

Posted on Fri, 13 Mar 2020 07:17:56 -0700 by ShaolinF