[c++] Printing 1 to 1000 without loop or conditionals

Task: Print numbers from 1 to 1000 without using any loop or conditional statements. Don't just write the printf() or cout statement 1000 times.

How would you do that using C or C++?

This question is related to c++ c printf

The answer is


There are plenty of abnormal exits due to stack overflows so far, but no heap ones yet, so here's my contribution:

#include <cstdio>
#include <cstdlib>
#include <sys/mman.h>
#include <sys/signal.h>
#define PAGE_SIZE 4096
void print_and_set(int i, int* s)
{
  *s = i;
  printf("%d\n", i);
  print_and_set(i + 1, s + 1);
}
void
sigsegv(int)
{
  fflush(stdout); exit(0);
}
int
main(int argc, char** argv)
{
  int* mem = reinterpret_cast<int*>
    (reinterpret_cast<char*>(mmap(NULL, PAGE_SIZE * 2, PROT_WRITE,
                                  MAP_PRIVATE | MAP_ANONYMOUS, 0, 0)) +
     PAGE_SIZE - 1000 * sizeof(int));
  mprotect(mem + 1000, PAGE_SIZE, PROT_NONE);
  signal(SIGSEGV, sigsegv);
  print_and_set(1, mem);
}

Not very good practice, and no error checks (for obvious reasons) but I don't think that is the point of the question!

There are plenty of other abnormal termination options, of course, some of which are simpler: assert(), SIGFPE (I think someone did that one), and so on.


How about another abnormal termination example. This time adjust stack size to run out at 1000 recursions.

int main(int c, char **v)
{
    static cnt=0;
    char fill[12524];
    printf("%d\n", cnt++);
    main(c,v);
}

On my machine it prints 1 to 1000

995
996
997
998
999
1000
Segmentation fault (core dumped)

#include <iostream>
#include <iterator>
using namespace std;

int num() { static int i = 1; return i++; }
int main() { generate_n(ostream_iterator<int>(cout, "\n"), 1000, num); }

Ugly C answer (unrolled for only one stack frame per power of 10):

#define f5(i) f(i);f(i+j);f(i+j*2);f(i+j*3);f(i+j*4)
void f10(void(*f)(int), int i, int j){f5(i);f5(i+j*5);}
void p1(int i){printf("%d,",i);}
#define px(x) void p##x##0(int i){f10(p##x, i, x);}
px(1); px(10); px(100);

void main()
{
  p1000(1);
}

The task never specified that the program must terminate after 1000.

void f(int n){
   printf("%d\n",n);
   f(n+1);
}

int main(){
   f(1);
}

(Can be shortened to this if you run ./a.out with no extra params)

void main(int n) {
   printf("%d\n", n);
   main(n+1);
}

#include <stdlib.h>
#include <stdio.h>
#include <math.h>

void (*f[2])(int v);

void p(int v) 
{ 
  printf("%d\n", v++); 
  f[(int)(floor(pow(v, v - 1000)))](v); 
}

void e(int v) 
{
  printf("%d\n", v);
}

int main(void)
{
  f[0] = p;
  f[1] = e;
  p(1);
}

A C++ variant of the accepted answer from the supposed duplicate:

void print(vector<int> &v, int ind)
{
    v.at(ind);
    std::cout << ++ind << std::endl;
    try
    {
        print(v, ind);
    }
    catch(std::out_of_range &e)
    {
    }
}

int main()
{
    vector<int> v(1000);
    print(v, 0);
}

Using system commands:

system("/usr/bin/seq 1000");

My little contribution to this fabulous set of answers (it returns zero) :

#include <stdio.h>

int main(int a)
{
    return a ^ 1001 && printf("%d\n", main(a+1)) , a-1;
}

Comma operator is FTW \o/


Obviously requires Windows/Visual Studio... But it works.

#include <stdio.h>
#include <Windows.h>

void print(int x)
{
    int y;

    printf("%d\n", x);
    __try
    {
        y = 1 / (x - 1000);
        print(x + 1);
    }
    __except(EXCEPTION_EXECUTE_HANDLER)
    {
        return;
    }
}

void main()
{
    print(1);
}

Just use std::copy() with a special iterator.

#include <algorithm>
#include <iostream>
#include <iterator>

struct number_iterator
{
    typedef std::input_iterator_tag iterator_category;
    typedef int                     value_type;
    typedef std::size_t             difference_type;
    typedef int*                    pointer;
    typedef int&                    reference;

    number_iterator(int v): value(v)                {}
    bool operator != (number_iterator const& rhs)   { return value != rhs.value;}
    number_iterator operator++()                    { ++value; return *this;}
    int operator*()                                 { return value; }
    int value;
};



int main()
{
    std::copy(number_iterator(1), 
              number_iterator(1001), 
              std::ostream_iterator<int>(std::cout, " "));
}

system("/usr/bin/env echo {1..1000}");

Since there is no restriction on bugs..

int i=1; int main() { int j=i/(i-1001); printf("%d\n", i++); main(); }

Or even better(?),

#include <stdlib.h>
#include <signal.h>

int i=1;
int foo() { int j=i/(i-1001); printf("%d\n", i++); foo(); }

int main()
{
        signal(SIGFPE, exit);
        foo();
}

We can launch 1000 threads, each printing one of the numbers. Install OpenMPI, compile using mpicxx -o 1000 1000.cpp and run using mpirun -np 1000 ./1000. You will probably need to increase your descriptor limit using limit or ulimit. Note that this will be rather slow, unless you have loads of cores!

#include <cstdio>
#include <mpi.h>
using namespace std;

int main(int argc, char **argv) {
  MPI::Init(argc, argv);
  cout << MPI::COMM_WORLD.Get_rank() + 1 << endl;
  MPI::Finalize();
}

Of course, the numbers won't necessarily be printed in order, but the question doesn't require them to be ordered.


#include "stdafx.h"
static n=1;
class number {
public:
    number () {
        std::cout << n++ << std::endl;
    }
};
int _tmain(int argc, _TCHAR* argv[])
{
    number X[1000];
    return 0;
}

You can use System() to print 1 to 1000 (by using DOS Command)

 include <process.h>
 void main()
 {
     system("cmd.exe /c for /l %x in (1, 1, 1000) do echo %x" );
 }

Run .exe(executable) file of your program which displays 1 to 1000

NOTE: Tested in WINDOWS


Well, what do you think about

int main(void) {
    printf(" 1 2 3 4 5 6 7 8");
    return 0;
}

I bet that 1000 was in binary and he was obviously checking the guy's CQ ( compSci Quotient)


Here are three solutions that I know. The second might be argued though.

// 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 be used for compile time constants only, (2) and (3) can be used for runtime expressions too — end edit. ]


As it is answer :)

printf("numbers from 1 to 1000 without using any loop or conditional statements. Don't just write the printf() or cout statement 1000 times.");


I've reformulated the great routine proposed by Bill to make it more universal:

void printMe () 
{
    int i = 1;
    startPrintMe:
    printf ("%d\n", i);
    void *labelPtr = &&startPrintMe + (&&exitPrintMe - &&startPrintMe) * (i++ / 1000);
    goto *labelPtr;
    exitPrintMe:
}

UPDATE: The second approach needs 2 functions:

void exitMe(){}
void printMe ()
{
    static int i = 1; // or 1001
    i = i * !!(1001 - i) + !(1001 - i); // makes function reusable
    printf ("%d\n", i);
    (typeof(void (*)())[]){printMe, exitMe} [!(1000-i++)](); // :)
}

For both cases you can initiate printing by simply calling

printMe();

Has been tested for GCC 4.2.


Using pointer arithmetic we can use automatic array initialization to 0 to our advantage.

#include <stdio.h>

void func();
typedef void (*fpa)();
fpa fparray[1002] = { 0 };

int x = 1;
void func() {
 printf("%i\n", x++);
 ((long)fparray[x] + &func)();
}

void end() { return; }

int main() {
 fparray[1001] = (fpa)(&end - &func);
 func();
 return 0;
}

Looks like it doesn't need to use loops

printf("1 10 11 100 101 110 111 1000\n");

template <int To, int From = 1>
struct printer {
    static void print() {
        cout << From << endl; 
        printer<To, From + 1>::print();
    }
};    

template <int Done>
struct printer<Done, Done> {
     static void print() {
          cout << Done << endl;
     }
};

int main() 
{
     printer<1000>::print();
}

Easy as pie! :P

#include <iostream>

static int current = 1;

struct print
{
    print() { std::cout << current++ << std::endl; }
};

int main()
{
    print numbers [1000];
}

Assuming the program is run in the usual way (./a.out) so that it has one argument, and ignoring the compiler type warnings then:

#include <stdio.h>
#include <stdlib.h>

void main(int i) {
    static void (*cont[2])(int) = { main, exit };
    printf("%d\n", i);
    cont[i/1000](i+1);
}

Stack overflow:

#include <stdio.h>

static void print_line(int i)
{   
 printf("%d\n", i); 
 print_line(i+1);
}   

int main(int argc, char* argv[])
{   
 //get up near the stack limit
 char tmp[ 8388608 - 32 * 1000 - 196 * 32 ];
 print_line(1);
} 

This is for an 8MB stack. Each function invocation appears to take about 32 bytes (hence the 32 * 1000). But then when I ran it I only got to 804 (hence the 196 * 32; perhaps the C runtime has other parts in the stack that you have to deduct also).


Here are my 2 solutions. First is C# and the second in C:

C#:

const int limit = 1000;

Action<int>[] actions = new Action<int>[2];
actions[0] = (n) => { Console.WriteLine(n); };
actions[1] = (n) => { Console.WriteLine(n);  actions[Math.Sign(limit - n-1)](n + 1); };

actions[1](0);

C:

#define sign(x) (( x >> 31 ) | ( (unsigned int)( -x ) >> 31 ))

void (*actions[3])(int);

void Action0(int n)
{
    printf("%d", n);
}

void Action1(int n)
{
    int index;
    printf("%d\n", n);
    index = sign(998-n)+1;
    actions[index](++n);
}

void main()
{
    actions[0] = &Action0;
    actions[1] = 0; //Not used
    actions[2] = &Action1;

    actions[2](0);
}

stand c++ concept, pass on gcc, vc

[root@localhost ~]# cat 1.cpp
#include <stdio.h>
#include <stdlib.h>

int i = 1;
void print(int arg0)
{
    printf("%d ",i);
    *(&arg0 - 1) = (int)print;
    *(&arg0 - i/1000) = (int)exit;
    i++;
}
int main(void) {
    int a[1000];
    print(0);
    return 0;
}

Running it:

[root@localhost ~]# g++ 1.cpp -o 1
[root@localhost ~]# ./1

1 2 ... 1000

This is standard C:

#include <stdio.h>

int main(int argc, char **argv)
{
    printf("%d ", argc);
    (void) (argc <= 1000 && main(argc+1, 0));

    return 0;
}

If you call it without arguments, it will print the numbers from 1 to 1000. Notice that the && operator is not a "conditional statement" even though it serves the same purpose.


If you're going to use compile-time recursion, then you probably also want to use divide & conquer to avoid hitting template depth limits:

#include <iostream>

template<int L, int U>
struct range
{
    enum {H = (L + U) / 2};
    static inline void f ()
    {
        range<L, H>::f ();
        range<H+1, U>::f ();
    }
};

template<int L>
struct range<L, L>
{
    static inline void f ()
    {
        std::cout << L << '\n';
    }
};

int main (int argc, char* argv[])
{
    range<1, 1000>::f ();
    return 0;
}

#include <stdio.h>
void main(int i){printf("%d\n",i)&&i++<1000&&(*((int*)&i-1)-=5);} 

another one:

#include <stdio.h>
int main(int i){return i<=1000&&printf("%d\n",i)&&main(++i);}

#include <stdio.h>
#include <stdlib.h>

void print(int n)
{
    int q;

    printf("%d\n", n);
    q = 1000 / (1000 - n);
    print(n + 1);
}

int main(int argc, char *argv[])
{
    print(1);
    return EXIT_SUCCESS;
}

It will eventually stop :P


#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];
}

Using macro compaction:

#include <stdio.h>

#define a printf("%d ",++i);
#define b a a a a a
#define c b b b b b
#define d c c c c c
#define e d d d d

int main ( void ) {
    int i = 0;
    e e
    return 0;
}

Or still better:

#include <stdio.h>

#define a printf("%d ",++i);
#define r(x) x x x x x
#define b r(r(r(a a a a)))

int main ( void ) {
    int i = 0;
    b b
    return 0;
}

If your C compiler supports blocks then you can write the following:

#include <stdio.h>

void ten(void (^b)(void)) { b();b();b();b();b();b();b();b();b();b(); }

int main() {
    __block int i = 0;
    ten(^{
        ten(^{
            ten(^{
                printf("%d\n", ++i);
            });
        });
    });
    return 0;
}

manglesky's solution is great, but not obfuscated enough. :-) So:

#include <stdio.h>
#define TEN(S) S S S S S S S S S S
int main() { int i = 1; TEN(TEN(TEN(printf("%d\n", i++);))) return 0; }

More preprocessor abuse:

#include <stdio.h>

#define A1(x,y) #x #y "0\n" #x #y "1\n" #x #y "2\n" #x #y "3\n" #x #y "4\n" #x #y "5\n" #x #y "6\n" #x #y "7\n" #x #y "8\n" #x #y "9\n"
#define A2(x) A1(x,1) A1(x,2) A1(x,3) A1(x,4) A1(x,5) A1(x,6) A1(x,7) A1(x,8) A1(x,9)
#define A3(x) A1(x,0) A2(x)
#define A4 A3(1) A3(2) A3(3) A3(4) A3(5) A3(6) A3(7) A3(8) A3(9)
#define A5 "1\n2\n3\n4\n5\n6\n7\n8\n9\n" A2() A4 "1000\n"

int main(int argc, char *argv[]) {
    printf(A5);
    return 0;
}

I feel so dirty; I think I'll go shower now.


After some tinkering I came up with this:

template<int n>
class Printer
{
public:
    Printer()
    {        
        std::cout << (n + 1) << std::endl;
        mNextPrinter.reset(new NextPrinter);
    }

private:
    typedef Printer<n + 1> NextPrinter;
    std::auto_ptr<NextPrinter> mNextPrinter;
};

template<>
class Printer<1000>
{
};

int main()
{
    Printer<0> p;
    return 0;
}

Later @ybungalobill's submission inspired me to this much simpler version:

struct NumberPrinter
{
    NumberPrinter()
    {
        static int fNumber = 1;
        std::cout << fNumber++ << std::endl;
    }
};


int main()
{
    NumberPrinter n[1000];
    return 0;
}

This only uses O(log N) stack and uses McCarthy evaluation http://en.wikipedia.org/wiki/Short-circuit_evaluation as its recursion condition.

#include <stdio.h>

int printN(int n) {
  printf("%d\n", n);
  return 1;
}

int print_range(int low, int high) {
  return ((low+1==high) && (printN(low)) ||
      (print_range(low,(low+high)/2) && print_range((low+high)/2, high)));
}

int main() {
  print_range(1,1001);
}

#include <stdio.h>

int show(int i) {
   printf("%d\n",i);
   return( (i>=1000) || show(i+1));
}


int main(int argc,char **argv) {
   return show(1);
}

The || operator short-circuits the recursive call to show when i is >= 1000.


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

c++ exploiting RAII

#include <iostream>
using namespace std;

static int i = 1;
struct a
{
    a(){cout<<i++<<endl;}
    ~a(){cout<<i++<<endl;}
}obj[500];

int main(){return 0;}

C exploiting macros

#include <stdio.h>

#define c1000(x) c5(c5(c5(c4(c2(x))))) 
#define c5(x) c4(x) c1(x) //or x x x x x
#define c4(x) c2(c2(x))   //or x x x x
#define c2(x) c1(x) c1(x) //or x x
#define c1(x) x

int main(int i){c1000(printf("%d\n",i++);)return 0;}

Edit: One more, this one is simple

#include <stdio.h>
#define p10(x) x x x x x x x x x x
int main(int i){p10(p10(p10(printf("%d\n",i++);)))return 0;} 

C exploiting recrusion

edit: this c code contains <= and ?: operators

#include <stdio.h>

int main(int i){return (i<=1000)?main(printf("%d\n",i++)*0 + i):0;}

This one actually compiles to assembly that doesn't have any conditionals:

#include <stdio.h>
#include <stdlib.h>

void main(int j) {
  printf("%d\n", j);
  (&main + (&exit - &main)*(j/1000))(j+1);
}


Edit: Added '&' so it will consider the address hence evading the pointer errors.

This version of the above in standard C, since it doesn't rely on arithmetic on function pointers:

#include <stdio.h>
#include <stdlib.h>

void f(int j)
{
    static void (*const ft[2])(int) = { f, exit };

    printf("%d\n", j);
    ft[j/1000](j + 1);
}

int main(int argc, char *argv[])
{
    f(1);
}

Easy as pie:

int main(int argc, char* argv[])
{
    printf(argv[0]);
}

method of execution:

printer.exe "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;101;102;103;104;105;106;107;108;109;110;111;112;113;114;115;116;117;118;119;120;121;122;123;124;125;126;127;128;129;130;131;132;133;134;135;136;137;138;139;140;141;142;143;144;145;146;147;148;149;150;151;152;153;154;155;156;157;158;159;160;161;162;163;164;165;166;167;168;169;170;171;172;173;174;175;176;177;178;179;180;181;182;183;184;185;186;187;188;189;190;191;192;193;194;195;196;197;198;199;200;201;202;203;204;205;206;207;208;209;210;211;212;213;214;215;216;217;218;219;220;221;222;223;224;225;226;227;228;229;230;231;232;233;234;235;236;237;238;239;240;241;242;243;244;245;246;247;248;249;250;251;252;253;254;255;256;257;258;259;260;261;262;263;264;265;266;267;268;269;270;271;272;273;274;275;276;277;278;279;280;281;282;283;284;285;286;287;288;289;290;291;292;293;294;295;296;297;298;299;300;301;302;303;304;305;306;307;308;309;310;311;312;313;314;315;316;317;318;319;320;321;322;323;324;325;326;327;328;329;330;331;332;333;334;335;336;337;338;339;340;341;342;343;344;345;346;347;348;349;350;351;352;353;354;355;356;357;358;359;360;361;362;363;364;365;366;367;368;369;370;371;372;373;374;375;376;377;378;379;380;381;382;383;384;385;386;387;388;389;390;391;392;393;394;395;396;397;398;399;400;401;402;403;404;405;406;407;408;409;410;411;412;413;414;415;416;417;418;419;420;421;422;423;424;425;426;427;428;429;430;431;432;433;434;435;436;437;438;439;440;441;442;443;444;445;446;447;448;449;450;451;452;453;454;455;456;457;458;459;460;461;462;463;464;465;466;467;468;469;470;471;472;473;474;475;476;477;478;479;480;481;482;483;484;485;486;487;488;489;490;491;492;493;494;495;496;497;498;499;500;501;502;503;504;505;506;507;508;509;510;511;512;513;514;515;516;517;518;519;520;521;522;523;524;525;526;527;528;529;530;531;532;533;534;535;536;537;538;539;540;541;542;543;544;545;546;547;548;549;550;551;552;553;554;555;556;557;558;559;560;561;562;563;564;565;566;567;568;569;570;571;572;573;574;575;576;577;578;579;580;581;582;583;584;585;586;587;588;589;590;591;592;593;594;595;596;597;598;599;600;601;602;603;604;605;606;607;608;609;610;611;612;613;614;615;616;617;618;619;620;621;622;623;624;625;626;627;628;629;630;631;632;633;634;635;636;637;638;639;640;641;642;643;644;645;646;647;648;649;650;651;652;653;654;655;656;657;658;659;660;661;662;663;664;665;666;667;668;669;670;671;672;673;674;675;676;677;678;679;680;681;682;683;684;685;686;687;688;689;690;691;692;693;694;695;696;697;698;699;700;701;702;703;704;705;706;707;708;709;710;711;712;713;714;715;716;717;718;719;720;721;722;723;724;725;726;727;728;729;730;731;732;733;734;735;736;737;738;739;740;741;742;743;744;745;746;747;748;749;750;751;752;753;754;755;756;757;758;759;760;761;762;763;764;765;766;767;768;769;770;771;772;773;774;775;776;777;778;779;780;781;782;783;784;785;786;787;788;789;790;791;792;793;794;795;796;797;798;799;800;801;802;803;804;805;806;807;808;809;810;811;812;813;814;815;816;817;818;819;820;821;822;823;824;825;826;827;828;829;830;831;832;833;834;835;836;837;838;839;840;841;842;843;844;845;846;847;848;849;850;851;852;853;854;855;856;857;858;859;860;861;862;863;864;865;866;867;868;869;870;871;872;873;874;875;876;877;878;879;880;881;882;883;884;885;886;887;888;889;890;891;892;893;894;895;896;897;898;899;900;901;902;903;904;905;906;907;908;909;910;911;912;913;914;915;916;917;918;919;920;921;922;923;924;925;926;927;928;929;930;931;932;933;934;935;936;937;938;939;940;941;942;943;944;945;946;947;948;949;950;951;952;953;954;955;956;957;958;959;960;961;962;963;964;965;966;967;968;969;970;971;972;973;974;975;976;977;978;979;980;981;982;983;984;985;986;987;988;989;990;991;992;993;994;995;996;997;998;999;1000"

The specification does not say that the sequence must be generated inside the code :)


#include <iostream>
#include <vector>

using namespace std;
#define N 10    //10 or 1000, doesn't matter

class A{
public:
    A(){
        //cout << "A(): " << m_ << endl;    //uncomment to show the difference between gcc and Microsoft C++ compiler
    }
    A(const A&){
        ++m_;
        cout << m_ << endl;     
    }
private:
    static int m_;  //global counter
};

int A::m_(0);  //initialization

int main(int argc, char* argv[])
{
    //Creates a vector with N elements. Printing is from the copy constructor, 
    //which is called exactly N times.
    vector<A> v(N);  
    return 0;   
}

Implementation note:
With gcc: One "master" element is created by the default constructor. Then the element is copied N times by the copy constructor.
With Microsoft C++ compiler: all the elements are created by default constructor and then copied by the copy constructor.


Don't know enough C(++) to write code, but you could use recursion instead of a loop. In order to avoid the condition you could use a datastructure which will throw an exception after the 1000th access. E.g. some kind of list with range checking where you increase/decrease the index on each recursion.

Judging from the comments there don't seem to be any rangechecking lists in C++?

Instead you could 1/n with n being a parameter to your recursive function, which gets reduced by 1 on each call. Start with 1000. The DivisionByZero Exception will stop your recursion


Note:

  • please look forward to get results.
  • that this program often bug.

Then

#include <iostream>
#include <ctime>

#ifdef _WIN32
#include <windows.h>
#define sleep(x) Sleep(x*1000)
#endif

int main() {
  time_t c = time(NULL);
retry:
  sleep(1);
  std::cout << time(NULL)-c << std::endl;
goto retry;
}

For C++ lovers

int main() {
  std::stringstream iss;
  iss << std::bitset<32>(0x12345678);
  std::copy(std::istream_iterator< std::bitset<4> >(iss), 
            std::istream_iterator< std::bitset<4> >(),
            std::ostream_iterator< std::bitset<4> >(std::cout, "\n")); 
}

A bit boring compared to others here, but probably what they're looking for.

#include <stdio.h>

int f(int val) {
    --val && f(val);
    return printf( "%d\n", val+1);
}

void main(void) {
    f(1000);
}

Recursion?

#include<stdio.h>
#define MAX 1000

int i = 0;
void foo(void) {
    if(i <= 1000) {
         printf("%d", i);
         i++;
    }
}
int main (void) {
    foo();
}

I don't suppose this is a "trick question" . . . "?:" isn't an conditional, it is an operator.

So use recursion and the ?: operator to detect the when to stop?

int recurse(i)
{
   printf("%d\n", i);
   int unused = i-1000?recurse(i+1):0;

}

recurse(1);

Or along a similar perverted line of thinking . . . the second clause in an "&" condition is only executed if the first value is true. So recurse something like this:

i-1000 & recurse(i+1);

Perhaps the interviewer considers that an expression instead of a conditional.


Nobody said it shouldn't segfault afterwards, right?

Note: this works correctly on my 64-bit Mac OS X system. For other systems, you will need to change the args to setrlimit and the size of spacechew accordingly. ;-)

(I shouldn't need to include this, but just in case: this is clearly not an example of good programming practice. It does, however, have the advantage that it makes use of the name of this site.)

#include <sys/resource.h>
#include <stdio.h>

void recurse(int n)
{
    printf("%d\n", n);
    recurse(n + 1);
}

int main()
{
    struct rlimit rlp;
    char spacechew[4200];

    getrlimit(RLIMIT_STACK, &rlp);
    rlp.rlim_cur = rlp.rlim_max = 40960;
    setrlimit(RLIMIT_STACK, &rlp);

    recurse(1);
    return 0; /* optimistically */
}

#include <stdio.h>

void nothing(int);
void next(int);
void (*dispatch[2])(int) = {next, nothing};

void nothing(int x) { }
void next(int x)
{
    printf("%i\n", x);
    dispatch[x/1000](x+1);
}

int main()
{
    next(1);
    return 0;
}

Neither loop nor conditional Statements and at least it doesn't crash on my machine :). Using with some pointer magic we have...

#include <stdlib.h>
#include <stdio.h>

typedef void (*fp) (void *, int );

void end(fp* v, int i){
    printf("1000\n");
    return;
}

void print(fp *v, int i)
{
    printf("%d\n", 1000-i);
    v[i-1] = (fp)print;
    v[0] = (fp)end;
    (v[i-1])(v, i-1);

}

int main(int argc, char *argv[])
{
    fp v[1000];

    print(v, 1000);

    return 0;
}

I am not going to write the code but just the idea. How about to make a thread that print a number per second, and then another thread kill the first thread after 1000 seconds?

note: the first thread generate numbers by recursion.


If POSIX solutions are accepted:

#include <stdio.h>
#include <signal.h>
#include <stdlib.h>
#include <sys/time.h>
#include <pthread.h>

static void die(int sig) {
    exit(0);
}

static void wakeup(int sig) {
    static int counter = 1;
    struct itimerval timer;
    float i = 1000 / (1000 - counter);

    printf("%d\n", counter++);

    timer.it_interval.tv_sec = 0;
    timer.it_interval.tv_usec = 0;
    timer.it_value.tv_sec = 0;
    timer.it_value.tv_usec = i; /* Avoid code elimination */
    setitimer(ITIMER_REAL, &timer, 0);
}

int main() {
    pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
    signal(SIGFPE, die);
    signal(SIGALRM, wakeup);
    wakeup(0);
    pthread_mutex_lock(&mutex);
    pthread_mutex_lock(&mutex); /* Deadlock, YAY! */
    return 0;
}

I hate to break it, but recursion and looping are essentially the same thing at the machine level.

The difference is the use of a JMP/JCC versus a CALL instruction. Both of which have roughly the same cycle times and flush the instruction pipeline.

My favorite trick for recursion was to hand-code a PUSH of a return address and use JMP to a function. The function then behaves normally, and returns at the end, but to somewhere else. This is really useful for parsing faster because it reduces instruction pipeline flushes.

The Original Poster was probably going for either a complete unroll, which the template guys worked out; or page memory into the terminal, if you know exactly where the terminal text is stored. The latter requires alot of insight and is risky, but takes almost no computational power and the code is free of nastiness like 1000 printfs in succession.


Trigger a fatal error! Here's the file, countup.c:

#include <stdio.h>
#define MAX 1000
int boom;
int foo(n) {
    boom = 1 / (MAX-n+1);
    printf("%d\n", n);
    foo(n+1);
}
int main() {
    foo(1);
}

Compile, then execute on a shell prompt:

$ ./countup
1
2
3
...
996
997
998
999
1000
Floating point exception
$

This does indeed print the numbers from 1 to 1000, without any loops or conditionals!


Should work on any machine that doesn't like 0 / 0. You could replace this with a null pointer reference if you need to. The program can fail after printing 1 to 1000, right?

#include <stdio.h>

void print_1000(int i);
void print_1000(int i) {
    int j;
    printf("%d\n", i);
    j = 1000 - i;
    j = j / j;
    i++;
    print_1000(i);
}

int main() {
    print_1000(1);
}

Using recursion, conditionals can be substituted using function pointer arithmetic:

#include <stdio.h>
#include <stdlib.h> // for: void exit(int CODE)

// function pointer
typedef void (*fptr)(int);

void next(int n)
{
        printf("%d\n", n);

        // pointer to next function to call
        fptr fp = (fptr)(((n != 0) * (unsigned int) next) +
                         ((n == 0) * (unsigned int) exit));

        // decrement and call either ``next'' or ``exit''
        fp(n-1);
}

int main()
{
        next(1000);
}

Note that there are no conditionals; n!=0 and n==0 are branchless operations. (Though, we perform a branch in the tail call).


Despite all the brilliant code seen here, I think that the only real answer is that it can't be done.

Why? Simple. Every single answer is, in fact, looping. Looping hidden as recursion is still looping. One look at the assembly code reveals this fact. Even reading and printing a text file with the numbers involves looping. Again, look at the machine code. Typing 1000 printf statements also means looping because printf itself has loops within it.

Can't be done.


I've read through all of these answers, and mine's different from all the others. It is standard C and uses integer division to select function pointers from an array. Moreover it compiles and executes correctly with no warnings and even passes 'splint' with no warnings.

I was, of course inspired by many of the other answers here. Even so, mine's better.

#include <stdio.h>
#include <stdlib.h>

static int x(/*@unused@*/ const char * format, ...) { exit(0); }

static void p(int v, int e) {
    static int (*a[])(const char *, ...) = { printf, x };
    (void)a[v/(e+1)]("%d\n", v);
    p(v+1, e);
}

int main(void) {
    p(1, 1000);
    return 0;
}

    static void Main(string[] args)
    {
        print(1000);
        System.Console.ReadKey();
    }

    static bool print(int val)
    {
        try
        {
            print( ((val/val)*val) - 1);
            System.Console.WriteLine(val.ToString());
        }
        catch (Exception ex)
        {
            return false;
        }
        return true;
    }

#include<iostream>
#include<stdexcept>

using namespace std;

int main(int arg)

{
    try

    {

        printf("%d\n",arg);
        int j=1/(arg-1000);
        main(arg+1);
    }

    catch(...)
    {
        exit(1);
    }
}

Javascript thrown in for fun. Includes an automatic stop at 1000:

var max = 1000;
var b = ["break"];
function increment(i) {
    var j = Math.abs(i - max);
    console.log(j);           
    b[(i/i) - 1].toString();
    i--;
    increment(i);    
}
increment(max);

I feel this answer will be very simple and easy to understand.

int print1000(int num=1)
{
    printf("%d\n", num);

    // it will check first the num is less than 1000. 
    // If yes then call recursive function to print
    return num<1000 && print1000(++num); 
}

int main()
{
    print1000();
    return 0;        
}

I'm wondering if the interviewer garbled a different question: Calculate the sum of the numbers from 1 to 1000 (or from any n through m) without using a loop. It also teaches a good lesson about analyzing problems. Printing the #s from 1 through 1000s in C will always rely on tricks that you may not use in a production program (tail recursion in Main, side effects of how truthiness is calculated, or preproc and template tricks.)

That would be a good spot-check to see if you've had any sort of mathematical training, because that old story about Gauss and his solution would probably be well known to anyone with any sort of math training.


With macros!

#include<stdio.h>
#define x001(a) a
#define x002(a) x001(a);x001(a)
#define x004(a) x002(a);x002(a)
#define x008(a) x004(a);x004(a)
#define x010(a) x008(a);x008(a)
#define x020(a) x010(a);x010(a)
#define x040(a) x020(a);x020(a)
#define x080(a) x040(a);x040(a)
#define x100(a) x080(a);x080(a)
#define x200(a) x100(a);x100(a)
#define x3e8(a) x200(a);x100(a);x080(a);x040(a);x020(a);x008(a)
int main(int argc, char **argv)
{
  int i = 0;
  x3e8(printf("%d\n", ++i));
  return 0;
}

Perhaps this is too obvious and easy to follow, but this is standard C++, does not dump stack and runs in O(n) time using O(n) memory.

#include <iostream>
#include <vector>

using namespace std;

int main (int argc, char** args) {
  vector<int> foo = vector<int>(1000);
  int terminator = 0;
 p:
  cout << terminator << endl; 
  try {
    foo.at(terminator++);
  } catch(...) {
    return 0;
  }
  goto p;
}

i think these code works perfectly right and its easy to understand you can print any like 1 to 100 or 1 to the final range. just put it in i and transfer it to call function.

int main()
{
    int i=1;
    call(i,i);
}

void call(int i,int j)
{
    printf("%d",i);
    sleep(1); // to see the numbers for delay
    j /= (j-1000);

    j = ++i;

    call(i,j);
}

so when j equals 1000 it gets divide by zero and it directly exits the program thats my idea to print the numbers

or much simpler code..

int main()
{
    static int i = 1;
    static int j = 1;
    printf("%d", i);
    sleep(1);
    j = ++i;
    j /= (j-1000);
    main();
}

OpenMP version (non-ordered of course):

#include <iostream>
#include <omp.h>

int main(int argc, char** argv)
{
#pragma omp parallel num_threads(1000)
    {           
#pragma omp critical
        {
            std::cout << omp_get_thread_num() << std::endl;
        }
    }

    return 0;
}

(Does not work with VS2010 OpenMP runtime (restricted to 64 threads), works however on linux with, e.g., the Intel compiler)

Here's an ordered version too:

#include <stdio.h>
#include <omp.h>

int main(int argc, char *argv[])
{
  int i = 1;
  #pragma omp parallel num_threads(1000)
  #pragma omp critical
    printf("%d ", i++);
  return 0;
}

Here's a POSIX variant using signals:

#include <stdio.h>
#include <signal.h>

void counter(int done)
{
        static int i;

        done = ++i / 1000;

        printf("%d\n", i);

        signal(SIGINT, (void (*)(int))(done * (int)SIG_DFL + (1-done) * (int)&counter));
        raise(SIGINT);
}

int main()
{
        signal(SIGINT, &counter);
        raise(SIGINT);

        return 0;
}

The interesting part is counter()'s call to signal(). Here, a new signal handler is installed: SIG_DFL if "done" is true, &counter otherwise.

To make this solution even more ridiculous, I used the signal handler's required int parameter to hold the result of a temporary computation. As a side-effect, the annoying "unused variable" warning disappears when compiling with gcc -W -Wall.


Here's a version that uses setjmp/longjmp, because someone had to do it:

#include <stdio.h>
#include <stdlib.h>
#include <setjmp.h>

void print(int i) {
    printf("%d\n", i);
}
typedef void (*func_t)(int);

int main() {
    jmp_buf buf;
    func_t f[] = {print, exit};
    int i = setjmp(buf)+1;
    f[i/1001](i);
    longjmp(buf, i);
    return 0;
}

#include <stdio.h>
int i = 0;
p()    { printf("%d\n", ++i); }
a()    { p();p();p();p();p(); }
b()    { a();a();a();a();a(); }
c()    { b();b();b();b();b(); }
main() { c();c();c();c();c();c();c();c(); return 0; }

I'm surprised nobody seems to have posted this -- I thought it was the most obvious way. 1000 = 5*5*5*8.


#include <stdio.h>

static void (*f[2])(int);
static void p(int i)
{ 
    printf("%d\n", i);
}

static void e(int i)
{
    exit(0);
}

static void r(int i)
{ 
    f[(i-1)/1000](i);
    r(i+1);
}

int main(int argc, char* argv[])
{
    f[0] = p;
    f[1] = e;
    r(1);
}

You can do it pretty simply using recursion and a forced error...

Also, pardon my horridly sloppy c++ code.

void print_number(uint number)
{
    try
    {
        print_number(number-1);
    }
    catch(int e) {}
    printf("%d", number+1);
}

void main()
{
    print_number(1001);
}

#include <stdio.h>
#define Out(i)       printf("%d\n", i++);
#define REP(N)       N N N N N N N N N N
#define Out1000(i)   REP(REP(REP(Out(i))));
void main()
{
 int i = 1;
 Out1000(i);
}

It's also possible to do it with plain dynamic dispatch (works in Java too):

#include<iostream>
using namespace std;

class U {
  public:
  virtual U* a(U* x) = 0; 
  virtual void p(int i) = 0;
  static U* t(U* x) { return x->a(x->a(x->a(x))); }
};

class S : public U {
  public:
  U* h;
  S(U* h) : h(h) {}
  virtual U* a(U* x) { return new S(new S(new S(h->a(x)))); }
  virtual void p(int i) { cout << i << endl; h->p(i+1); }
};

class Z : public U {
  public:
  virtual U* a(U* x) { return x; }
  virtual void p(int i) {}
};

int main(int argc, char** argv) {
  U::t(U::t(U::t(new S(new Z()))))->p(1);
}

If you don't mind leading zeros, then lets skip printf

#include <stdlib.h>
void l();
void n();
void (*c[3])() = {l, n, exit};
char *a;
void (*x)();
char b[] = "0000";
void run() { x(); run(); }
#define C(d,s,i,j,f) void d() { s;x = c[i]; a = j;f; }
C(l, puts(b), 1+(a<b), b+3,)
C(n, int v = *a - '0' + 1; *a = v%10 + '0', v/10, a-1,)
C(main,,1,b+3, run())

#include <stdio.h>
int main(int argc, char** argv)
{
printf("numbers from 1 to 1000\n");
}

#include <stdio.h>
#include <assert.h>

void foo( int n )
{
 printf("%d\n", n);
 assert( n > 0 );
 foo(--n); 
}

int main()
{
 foo( 1000 );
 getchar();
}

template <int remaining>
void print(int v) {
 printf("%d\n", v);
 print<remaining-1>(v+1);
}

template <>
void print<0>(int v) {
}

print<1000>(1);

a dirty code :s

used xor and array of function pointers.

#include <stdio.h>
#include <stdlib.h>

typedef void (*fn)(int);
int lst[1001];

void print (int n)
{
  printf ("%d ", n+1);
  go (n+1);
}

void go (int n)
{
  ((fn)(((long)print)^((long)lst[n])))(n);
}

int main ()
{
  lst[1000] = ((long)print)^((long)exit);
  go (0);
}

Inspired by Orion_G's answer and reddit discussion; uses function pointers and binary arithmetic:

#include <stdio.h>
#define b10 1023
#define b3 7

typedef void (*fp) (int,int);

int i = 0;
void print(int a, int b) { printf("%d\n",++i); }
void kick(int a, int b) { return; }

void rec(int,int);
fp r1[] = {print, rec} ,r2[] = {kick, rec};
void rec(int a, int b) {
  (r1[(b>>1)&1])(b10,b>>1);
  (r2[(a>>1)&1])(a>>1,b);
}

int main() {
  rec(b10,b3);
  return 1;
}

Fun with function pointers (none of that new-fangled TMP needed):

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <limits.h>


#define MSB(typ) ((sizeof(typ) * CHAR_BIT) - 1)

void done(int x, int y);
void display(int x, int y);

void (*funcs[])(int,int)  = {
    done,
    display
};

void done(int x, int y)
{
    exit(0);
}

void display(int x, int limit)
{
    printf( "%d\n", x);
    funcs[(((unsigned int)(x-limit)) >> MSB(int)) & 1](x+1, limit);
}


int main()
{
    display(1, 1000);
    return 0;
}

As a side note: I took the prohibition against conditionals to extend to logical and relational operators as well. If you allow logical negation, the recursive call can be simplified to:

funcs[!!(limit-1)](x+1, limit-1);

With plain C:

#include<stdio.h>

/* prints number  i */ 
void print1(int i) {
    printf("%d\n",i);
}

/* prints 10 numbers starting from i */ 
void print10(int i) {
    print1(i);
    print1(i+1);
    print1(i+2);
    print1(i+3);
    print1(i+4);
    print1(i+5);
    print1(i+6);
    print1(i+7);
    print1(i+8);
    print1(i+9);
}

/* prints 100 numbers starting from i */ 
void print100(int i) {
    print10(i);
    print10(i+10);
    print10(i+20);
    print10(i+30);
    print10(i+40);
    print10(i+50);
    print10(i+60);
    print10(i+70);
    print10(i+80);
    print10(i+90);
}

/* prints 1000 numbers starting from i */ 
void print1000(int i) {
    print100(i);
    print100(i+100);
    print100(i+200);
    print100(i+300);
    print100(i+400);
    print100(i+500);
    print100(i+600);
    print100(i+700);
    print100(i+800);
    print100(i+900);
}


int main() {
        print1000(1);
        return 0;
}

Of course, you can implement the same idea for other bases (2: print2 print4 print8 ...) but the number 1000 here suggested base 10. You can also reduce a little the number of lines adding intermediate functions: print2() print10() print20() print100() print200() print1000() and other equivalent alternatives.


#include <iostream>

using namespace std;

template<int N>
void func()
{
        func<N-1>();
        cout << N << "\t";
}

template<>
void func<1>()
{
        cout << 1 << "\t";
}

int main()
{
        func<1000>();
        cout << endl;
        return 0;
}

It is hard to see through all the solutions that have already been proposed, so maybe this is a duplicate.

I wanted to have something relatively simple just with pure C and not C++. It uses recursion, but contrary to other solutions that I have seen it only does recursion of logarithmic depth. The use of conditionals is avoided by a table lookup.

typedef void (*func)(unsigned, unsigned);
void printLeaf(unsigned, unsigned);
void printRecurse(unsigned, unsigned);


func call[2] = { printRecurse, printLeaf };

/* All array members that are not initialized 
   explicitly are implicitly initialized to 0 
   according to the standard. */
unsigned strat[1000] = { 0, 1 };


void printLeaf(unsigned start, unsigned len) {
  printf("%u\n", start);
}

void printRecurse(unsigned start, unsigned len) {
  unsigned half0 = len / 2;
  unsigned half1 = len - half0;
  call[strat[half0]](start, half0);
  call[strat[half1]](start + half0, half1);
}

int main (int argc, char* argv[]) {
  printRecurse(0, 1000);
}

This could even be done dynamically by using just a pointer. Relevant changes:

unsigned* strat = 0;

int main (int argc, char* argv[]) {
  strat = calloc(N, sizeof(*strat));
  strat[1] = 1;
  printRecurse(0, N);
}

You don't really need anything more than basic string processing:

#include <iostream>
#include <algorithm>

std::string r(std::string s, char a, char b)
{
    std::replace(s.begin(), s.end(), a, b);
    return s;
}

int main()
{
    std::string s0 = " abc\n";
    std::string s1 = r(s0,'c','0')+r(s0,'c','1')+r(s0,'c','2')+r(s0,'c','3')+r(s0,'c','4')+r(s0,'c','5')+r(s0,'c','6')+r(s0,'c','7')+r(s0,'c','8')+r(s0,'c','9');
    std::string s2 = r(s1,'b','0')+r(s1,'b','1')+r(s1,'b','2')+r(s1,'b','3')+r(s1,'b','4')+r(s1,'b','5')+r(s1,'b','6')+r(s1,'b','7')+r(s1,'b','8')+r(s1,'b','9');
    std::string s3 = r(s2,'a','0')+r(s2,'a','1')+r(s2,'a','2')+r(s2,'a','3')+r(s2,'a','4')+r(s2,'a','5')+r(s2,'a','6')+r(s2,'a','7')+r(s2,'a','8')+r(s2,'a','9');
    std::cout << r(r(s1,'a',' '),'b',' ').substr(s0.size())
          << r(s2,'a',' ').substr(s0.size()*10)
          << s3.substr(s0.size()*100)
          << "1000\n";
}

Simple C version, terminates at 1000:

int print_stuff(int count) {
   printf("%d\n", count);
   return (count ^ 1000) && print_stuff(count+1);
 }

 int main(int argc, char *argv[]) {
   print_stuff(1);
   return 0;
 }

Function pointer (ab)use. No preprocessor magic to increase output. ANSI C.

#include <stdio.h>

int i=1;

void x10( void (*f)() ){
    f(); f(); f(); f(); f();
    f(); f(); f(); f(); f();
}

void I(){printf("%i ", i++);}
void D(){ x10( I ); }
void C(){ x10( D ); }
void M(){ x10( C ); }

int main(){
    M();
}

#include<stdio.h>
int b=1;
int printS(){    
    printf("%d\n",b);
    b++;
    (1001-b) && printS();
}
int main(){printS();}

        #include <stdio.h>
        #include <stdlib.h>
        #include <string.h>

        typedef void(*word)(int);

        word words[1024];

        void print(int i) {
                printf("%d\n", i);
                words[i+1](i+1);
        }

        void bye(int i) {
                exit(0);
        }

        int main(int argc, char *argv[]) {
                words[0] = print;
                words[1] = print;
                memcpy(&words[2], &words[0], sizeof(word) * 2); // 0-3
                memcpy(&words[4], &words[0], sizeof(word) * 4); // 0-7
                memcpy(&words[8], &words[0], sizeof(word) * 8); // 0-15
                memcpy(&words[16], &words[0], sizeof(word) * 16); // 0-31
                memcpy(&words[32], &words[0], sizeof(word) * 32); // 0-63
                memcpy(&words[64], &words[0], sizeof(word) * 64); // 0-127
                memcpy(&words[128], &words[0], sizeof(word) * 128); // 0-255
                memcpy(&words[256], &words[0], sizeof(word) * 256); // 0-511
                memcpy(&words[512], &words[0], sizeof(word) * 512); // 0-1023
                words[1001] = bye;
                words[1](1);
        }

I'm not writing the printf statement 1000 times!

printf("1\n2\n3\n4\n5\n6\n7\n8\n9\n10\n11\n12\n13\n14\n15\n16\n17\n18\n19\n20\n21\n22\n23\n24\n25\n26\n27\n28\n29\n30\n31\n32\n33\n34\n35\n36\n37\n38\n39\n40\n41\n42\n43\n44\n45\n46\n47\n48\n49\n50\n51\n52\n53\n54\n55\n56\n57\n58\n59\n60\n61\n62\n63\n64\n65\n66\n67\n68\n69\n70\n71\n72\n73\n74\n75\n76\n77\n78\n79\n80\n81\n82\n83\n84\n85\n86\n87\n88\n89\n90\n91\n92\n93\n94\n95\n96\n97\n98\n99\n100\n101\n102\n103\n104\n105\n106\n107\n108\n109\n110\n111\n112\n113\n114\n115\n116\n117\n118\n119\n120\n121\n122\n123\n124\n125\n126\n127\n128\n129\n130\n131\n132\n133\n134\n135\n136\n137\n138\n139\n140\n141\n142\n143\n144\n145\n146\n147\n148\n149\n150\n151\n152\n153\n154\n155\n156\n157\n158\n159\n160\n161\n162\n163\n164\n165\n166\n167\n168\n169\n170\n171\n172\n173\n174\n175\n176\n177\n178\n179\n180\n181\n182\n183\n184\n185\n186\n187\n188\n189\n190\n191\n192\n193\n194\n195\n196\n197\n198\n199\n200\n201\n202\n203\n204\n205\n206\n207\n208\n209\n210\n211\n212\n213\n214\n215\n216\n217\n218\n219\n220\n221\n222\n223\n224\n225\n226\n227\n228\n229\n230\n231\n232\n233\n234\n235\n236\n237\n238\n239\n240\n241\n242\n243\n244\n245\n246\n247\n248\n249\n250\n251\n252\n253\n254\n255\n256\n257\n258\n259\n260\n261\n262\n263\n264\n265\n266\n267\n268\n269\n270\n271\n272\n273\n274\n275\n276\n277\n278\n279\n280\n281\n282\n283\n284\n285\n286\n287\n288\n289\n290\n291\n292\n293\n294\n295\n296\n297\n298\n299\n300\n301\n302\n303\n304\n305\n306\n307\n308\n309\n310\n311\n312\n313\n314\n315\n316\n317\n318\n319\n320\n321\n322\n323\n324\n325\n326\n327\n328\n329\n330\n331\n332\n333\n334\n335\n336\n337\n338\n339\n340\n341\n342\n343\n344\n345\n346\n347\n348\n349\n350\n351\n352\n353\n354\n355\n356\n357\n358\n359\n360\n361\n362\n363\n364\n365\n366\n367\n368\n369\n370\n371\n372\n373\n374\n375\n376\n377\n378\n379\n380\n381\n382\n383\n384\n385\n386\n387\n388\n389\n390\n391\n392\n393\n394\n395\n396\n397\n398\n399\n400\n401\n402\n403\n404\n405\n406\n407\n408\n409\n410\n411\n412\n413\n414\n415\n416\n417\n418\n419\n420\n421\n422\n423\n424\n425\n426\n427\n428\n429\n430\n431\n432\n433\n434\n435\n436\n437\n438\n439\n440\n441\n442\n443\n444\n445\n446\n447\n448\n449\n450\n451\n452\n453\n454\n455\n456\n457\n458\n459\n460\n461\n462\n463\n464\n465\n466\n467\n468\n469\n470\n471\n472\n473\n474\n475\n476\n477\n478\n479\n480\n481\n482\n483\n484\n485\n486\n487\n488\n489\n490\n491\n492\n493\n494\n495\n496\n497\n498\n499\n500\n501\n502\n503\n504\n505\n506\n507\n508\n509\n510\n511\n512\n513\n514\n515\n516\n517\n518\n519\n520\n521\n522\n523\n524\n525\n526\n527\n528\n529\n530\n531\n532\n533\n534\n535\n536\n537\n538\n539\n540\n541\n542\n543\n544\n545\n546\n547\n548\n549\n550\n551\n552\n553\n554\n555\n556\n557\n558\n559\n560\n561\n562\n563\n564\n565\n566\n567\n568\n569\n570\n571\n572\n573\n574\n575\n576\n577\n578\n579\n580\n581\n582\n583\n584\n585\n586\n587\n588\n589\n590\n591\n592\n593\n594\n595\n596\n597\n598\n599\n600\n601\n602\n603\n604\n605\n606\n607\n608\n609\n610\n611\n612\n613\n614\n615\n616\n617\n618\n619\n620\n621\n622\n623\n624\n625\n626\n627\n628\n629\n630\n631\n632\n633\n634\n635\n636\n637\n638\n639\n640\n641\n642\n643\n644\n645\n646\n647\n648\n649\n650\n651\n652\n653\n654\n655\n656\n657\n658\n659\n660\n661\n662\n663\n664\n665\n666\n667\n668\n669\n670\n671\n672\n673\n674\n675\n676\n677\n678\n679\n680\n681\n682\n683\n684\n685\n686\n687\n688\n689\n690\n691\n692\n693\n694\n695\n696\n697\n698\n699\n700\n701\n702\n703\n704\n705\n706\n707\n708\n709\n710\n711\n712\n713\n714\n715\n716\n717\n718\n719\n720\n721\n722\n723\n724\n725\n726\n727\n728\n729\n730\n731\n732\n733\n734\n735\n736\n737\n738\n739\n740\n741\n742\n743\n744\n745\n746\n747\n748\n749\n750\n751\n752\n753\n754\n755\n756\n757\n758\n759\n760\n761\n762\n763\n764\n765\n766\n767\n768\n769\n770\n771\n772\n773\n774\n775\n776\n777\n778\n779\n780\n781\n782\n783\n784\n785\n786\n787\n788\n789\n790\n791\n792\n793\n794\n795\n796\n797\n798\n799\n800\n801\n802\n803\n804\n805\n806\n807\n808\n809\n810\n811\n812\n813\n814\n815\n816\n817\n818\n819\n820\n821\n822\n823\n824\n825\n826\n827\n828\n829\n830\n831\n832\n833\n834\n835\n836\n837\n838\n839\n840\n841\n842\n843\n844\n845\n846\n847\n848\n849\n850\n851\n852\n853\n854\n855\n856\n857\n858\n859\n860\n861\n862\n863\n864\n865\n866\n867\n868\n869\n870\n871\n872\n873\n874\n875\n876\n877\n878\n879\n880\n881\n882\n883\n884\n885\n886\n887\n888\n889\n890\n891\n892\n893\n894\n895\n896\n897\n898\n899\n900\n901\n902\n903\n904\n905\n906\n907\n908\n909\n910\n911\n912\n913\n914\n915\n916\n917\n918\n919\n920\n921\n922\n923\n924\n925\n926\n927\n928\n929\n930\n931\n932\n933\n934\n935\n936\n937\n938\n939\n940\n941\n942\n943\n944\n945\n946\n947\n948\n949\n950\n951\n952\n953\n954\n955\n956\n957\n958\n959\n960\n961\n962\n963\n964\n965\n966\n967\n968\n969\n970\n971\n972\n973\n974\n975\n976\n977\n978\n979\n980\n981\n982\n983\n984\n985\n986\n987\n988\n989\n990\n991\n992\n993\n994\n995\n996\n997\n998\n999\n1000\n");

You're welcome ;)


#include <stdio.h>
int main() { printf("numbers from 1 to 1000"); return 0; }

It's like that other riddle about english words that end in "gry", right?.


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

It doesn't print all the numbers, but it does "Print numbers from 1 to 1000." Ambiguous question for the win! :)


#include <stdio.h>

typedef void (*fp) (int);

void stop(int i)
{
   printf("\n");
}

void next(int i);

fp options[2] = { next, stop };

void next(int i)
{
   printf("%d ", i);
   options[i/1000](++i);
}

int main(void)
{
   next(1);
   return 0;
}

EDIT 2:

I removed undefined behaviors from code. Thanks to @sehe for notice.

No loops, recursions, conditionals and everything standard C ... (qsort abuse):

#include <stdio.h>
#include <stdlib.h>

int numbers[51] = {0};

int comp(const void * a, const void * b){
    numbers[0]++;
    printf("%i\n", numbers[0]);
    return 0;
}

int main()
{
  qsort(numbers+1,50,sizeof(int),comp);
  comp(NULL, NULL);
  return 0;
}

#include <boost/mpl/range_c.hpp>
#include <boost/mpl/for_each.hpp>
#include <boost/lambda/lambda.hpp>
#include <iostream>

int main()
{
  boost::mpl::for_each<boost::mpl::range_c<unsigned, 1, 1001> >(std::cout << boost::lambda::_1 << '\n');
  return(0);
}

Put the 1 to 1000 in a file "file"

int main()
{
    system("cat file");
    return 0;
 }

Preprocessor abuse!

#include <stdio.h>

void p(int x) { printf("%d\n", x); }

#define P5(x) p(x); p(x+1); p(x+2); p(x+3); p(x+4);
#define P25(x) P5(x) P5(x+5) P5(x+10) P5(x+15) P5(x+20)
#define P125(x) P25(x) P25(x+50) P25(x+75) P25(x+100)
#define P500(x) P125(x) P125(x+125) P125(x+250) P125(x+375)

int main(void)
{
  P500(1) P500(501)
  return 0;
}

The preprocessed program (see it with gcc -E input.c) is amusing.


I'm assuming, due to the nature of this question that extensions are not excluded?

Also, I'm surprised that so far no one used goto.

int main () {
    int i = 0;
    void * addr[1001] = { [0 ... 999] = &&again};
    addr[1000] = &&end;
again:
    printf("%d\n", i + 1);
    goto *addr[++i];
end:
    return 0;
}

Ok, so technically it is a loop - but it's no more a loop than all the recursive examples so far ;)


I missed all the fun, all the good C++ answers have already been posted !

This is the weirdest thing I could come up with, I wouldn't bet it's legal C99 though :p

#include <stdio.h>

int i = 1;
int main(int argc, char *argv[printf("%d\n", i++)])
{
  return (i <= 1000) && main(argc, argv);
}

Another one, with a little cheating :

#include <stdio.h>
#include <boost/preprocessor.hpp>

#define ECHO_COUNT(z, n, unused) n+1
#define FORMAT_STRING(z, n, unused) "%d\n"

int main()
{
    printf(BOOST_PP_REPEAT(1000, FORMAT_STRING, ~), BOOST_PP_ENUM(LOOP_CNT, ECHO_COUNT, ~));
}

Last idea, same cheat :

#include <boost/preprocessor.hpp>
#include <iostream>

int main()
{
#define ECHO_COUNT(z, n, unused) BOOST_PP_STRINGIZE(BOOST_PP_INC(n))"\n"
    std::cout << BOOST_PP_REPEAT(1000, ECHO_COUNT, ~) << std::endl;
}

you can use recursion .

like this:

void Print(int n)
{
  cout<<n<<" ";   
  if(n>1000)
     return
  else
     return Print(n+1)
}    

int main ()
{
  Print(1);
}

Amazing how easy it becomes if you drop the "has to be in C or C++" requirement:

Unix shell:

echo {1..1000} | tr ' ' '\n'

or

yes | nl | awk '{print $1}' | head -1000

If you're running on a Unix variant that doesn't have the yes command, use some other process that generates at least 1000 lines:

find / 2> /dev/null | nl | awk '{print $1}' | head -1000

or

cat /dev/zero | uuencode - | nl | awk '{print $1}' | head -1000

or

head -1000 /etc/termcap | nl -s: | cut -d: -f1

Examples related to c++

Method Call Chaining; returning a pointer vs a reference? How can I tell if an algorithm is efficient? Difference between opening a file in binary vs text How can compare-and-swap be used for a wait-free mutual exclusion for any shared data structure? Install Qt on Ubuntu #include errors detected in vscode Cannot open include file: 'stdio.h' - Visual Studio Community 2017 - C++ Error How to fix the error "Windows SDK version 8.1" was not found? Visual Studio 2017 errors on standard headers How do I check if a Key is pressed on C++

Examples related to c

conflicting types for 'outchar' Can't compile C program on a Mac after upgrade to Mojave Program to find largest and second largest number in array Prime numbers between 1 to 100 in C Programming Language In c, in bool, true == 1 and false == 0? How I can print to stderr in C? Visual Studio Code includePath "error: assignment to expression with array type error" when I assign a struct field (C) Compiling an application for use in highly radioactive environments How can you print multiple variables inside a string using printf?

Examples related to printf

How I can print to stderr in C? How can you print multiple variables inside a string using printf? Unsigned values in C How to print multiple variable lines in Java Scanf/Printf double variable C Format specifier %02x %i or %d to print integer in C using printf()? What is the printf format specifier for bool? printf() prints whole array Printf width specifier to maintain precision of floating-point value