My First C Program


My first C program was somewhat of a revelation for me - enough that I still remember the afternoon that I wrote it, more than a decade later.

With some JavaScript, Visual Basic, Python, and Java under my belt, I set out to learn C++; after all, that is what real programs are written in, right?

I had been studying algorithms as well, to fill the gaps in my self-taught computer-science knowledge, and one afternoon I decided to see if I could whip up an in-place quicksort in C, from memory.

Working in Notepad, I made a little main program and compiled it from the command line. I don't remember which compiler I was using - this was on Windows. The program just did this:

  • Read an integer command-line argument - the array size
  • Allocate an int-array of the given size
  • Fill the array with random integers
  • Sort the array, in-place
  • Loop through the array to check that is really is sorted
  • Print out "OK", or something like that.
After a few minor hiccups, I was delighted when the program compiled, and my first run, with a short array (100 elements, maybe - I don't remember), sorted correctly.

But I was suspicious - "OK" was being printed, but was it really working? I examined the code carefully, and managed to convince myself that it could not possibly print OK unless the array really was sorted. So I started trying larger inputs.

1000. No problem. Running my program from the command-line, there was no perceptible delay between hitting Return, and "OK" being printed out.

10000. Same thing.

100K. Then a million. Then I know something is very wrong. The program is simply printing out "OK" immediately. There should be a pause while it works, before the result is printed. It cannot possibly be sorting a million integers more-or-less instantly.

I examine the code again, with a fine-tooth comb, looking for any possible way that it could be just jumping to the end. But the code is simple and clear - I can't see any way that it could possibly not be working. This is getting frustrating.

Finally I decide to crank it up one more notch, just to be really, really sure. Ten million integers. I type in the command and press return. Again, it prints "OK" - but this time there is an ever-so- brief delay.

And in that moment - in that brief, sub-second moment before "OK" appears on my screen - everything changes. In that tiny pause, I am bowled over by the realization of just how fast - how astoundingly, mind-bendingly fast - modern computers are. I really can sort a million integers faster than I can blink.

A whole world of possibilities opened up for me in that instant. Until that moment I had been wrapped in the safe warm layers of interpreters and runtimes and frameworks. Because of that, I had never really had a feel for just how fast the hardware underneath could be. It took the bare-metal power of C to reveal that to me.