9 ms·
Stack Overflow: Printing 1 to 1000 in C
- RodgerTheGreat 16y agohow about a simple implementation in Forth? : o dup . cr 1+ ; : t o o o o o o o o o o ; : h t t t t t t t t t t ; : thousand h h h h h h h h h h drop ; 1 thousand
- silvajoao 16y ago#include <stdio.h> #define print printf("%d\n", n++); #define times2(x) x x #define times5(x) x x x x x #define pow3(x,f) x(x(x(f))) int main() { int n = 1; pow3(times2, pow3(times5, print)); return 0; }
- spirit23 16y ago//https://gist.github.com/870150 https://gist.github.com/870150 (function(max){ new Array(max + 1).join(' ').replace(/\s/g, function(c, i){ console.log(i + 1); }) })(1000)
- jrockway 16y agoToo bad the site is currently too slow for me to close as "not a real question".
- jedsmith 16y agoIt was tried when it was new[1]. To me, abuse of vote to close is up there with deletionism on Wikipedia as making no sense, particularly in this case. [1]: http://stackoverflow.com/posts/4568645/revisions http://stackoverflow.com/posts/4568645/revisions
- gnaritas 16y agoDeletion-ism makes perfect sense, it maintains a high signal to noise ratio.
- flatline 16y agoMy problem with this is that filters (e.g. search, tagging, ranking) give the same result without destroying information which is not, strictly speaking, noise.
- gnaritas 16y agoNo they don't, noise drowns out signal, see Google's problem with spam and splogs.
- maxbRuns 16y agomore like a high ratio of one person's preferred signal to other signals
- gnaritas 16y agoBy that metric, spam is signal because some people (spammers) want it.
- Dylan16807 16y agoThey don't want it, they want people to see it.
- 16y ago
- RiderOfGiraffes 16y ago... without conditionals. Cute puzzle, nice to see some inventive torturing of C, and various dialects that people believe are C.
- chops 16y agoand various dialects that people believe are C. To be fair, the SO question specifies "using C or C++", not just C.
- RiderOfGiraffes 16y agoTrue. At a glance I'm suspicious that some might truly be in neither, but I'm not really bothered to check. Any Language Lawyers around?
- nathanb 16y agoWithout specifying dialect (ANSI C, C99, etc.), I believe "valid C" really only means "some C compiler somewhere will accept it without generating errors".
- TillE 16y agoSomeone claims the second answer "obviously" isn't C, which I don't understand. GCC 4.5.2 compiles it without complaint. Is pointer arithmetic not allowed? Or calling main()?
- tspiteri 16y agoI'm not sure pointer arithmetic on function pointers is standard C. Using the -pedantic flag, gcc 4.5.2 does give a "warning: pointer to a function used in subtraction".
- emillon 16y agoThe paragraph on pointer differences (ANSI C99 6.5.6§9) states that : "both shall point to elements of the same array object, or one past the last element of the array object […] The size of the result is implementation-defined, and its type (a signed integer type) is ptrdiff_t". So, for an array of function pointer that would be legal behaviour, but for pointers to plain functions, it is undefined behaviour.
- afhof 16y agoObvious, but passing arguments to this will cause it to break. One other mod: (j/1000) could be replaced with (j>999) which is still non conditional, but faster.
- dchest 16y agoWell, just move the logic into its own function. #include <stdio.h> #include <stdlib.h> void pr(int j) { printf("%d\n", j); (pr + (exit - pr)*(j/1000))(j+1); } int main(int argc, char** argv) { pr(1); return 0; }
- acqq 16y agoI like it this way, it compiles on the compilers where the parent's doesn't (see http://news.ycombinator.com/item?id=2323964 http://news.ycombinator.com/item?id=2323964), I believe it fits to all standards, doesn't depend on any undefined behavior, it doesn't assume any convenient type size, it doesn't call exit, it doesn't crash and also it doesn't use any relational operators. It even uses only two arithmetic operators, and only on integers. #include <stdio.h> #include <stdlib.h> int pk( int i ) { static int (*v[])( int ) = { pk, abs }; printf( "%d\n", i ); return v[ i/1000 ]( i+1 ); } int main( void ) { pk( 1 ); return 0; }
- acqq 16y agoAnd interestingly enough Perl version can be almost the same, only without declarations: use POSIX; sub pk { print "$_[0]\n"; return ( \&pk, \&fabs )[ $_[0] / 1000 ]( $_[0] + 1 ); } pk( 1 );
- onedognight 16y agoFWIW, there's no need to use a library. perl -e '($pk=sub { print "$_[0]\n"; ($pk, sub{}) [$_[0]/1000] ($_[0]+1) }) -> (1)'
- artmageddon 16y agoMy favorite response: The real answer is "don't work there".
- HelloBeautiful 16y ago>> The real answer is "don't work there , if you have to ask this question ;-)"
- silentbicycle 16y agoA comment on the question says: "Why do interview questions always want you to write code that you shouldn't realistically write in application?" To prepare you for the code they shouldn't realistically have in production. Oh.
- efnx 16y agoI just learned a little more about C thanks to this. Compiling does cause a warning, though: gcc printy.c printy.c: In function ‘main’: printy.c:4: warning: return type of ‘main’ is not ‘int’
- oakenshield 16y agoIt's an abuse of the standard (c90 and c99). main is supposed to return int and take either no arg or two args, but I think a lot of legacy code violates this, so most compilers let you off with a warning. That said, "-Wall -Werror" are two useful things to always add to your gcc invokation.
- ahlatimer 16y agoPreviously posted and discussed: http://news.ycombinator.com/item?id=2062058 http://news.ycombinator.com/item?id=2062058
- kunjaan 16y agoprintf "numbers from 1 to 1000 without using any loop or conditional statements. Don't just write the printf() or cout statement 1000 times.\n How would you do that using C or C++?"
- deleted 16y ago[deleted]
- jedbrown 16y agoIn what sense do these lack conditionals?
- deleted 16y ago[deleted]
- RodgerTheGreat 16y agoI'm also rather confused as to what "doesn't work in Java". The logical conjunction operator does short-circuit, it's merely restricted to the boolean type. Since you aren't using the result, it doesn't matter: static boolean print1000(int n) { System.out.format("%d\n", n); return n<1000 && print1000(n+1); } public static void main(String[] args) { print1000(1); }
- lysium 16y agoIMHO, `&&` and `try` are conditionals, even if they lack the word `if`. :-)
- KeithMajhor 16y agoWell in that sense I'd say that "ft[j/1000](j + 1)" is a conditional too.
- ajays 16y agoHow would you do the same in other languages? It would be interesting to see the same question answered in Python, Perl, Java, etc. etc. Just as a fun thought exercise, and not to get into language flamewars.
- 3pt14159 16y ago1.upto 1000 {|n| puts n} # ruby ftw
- ajays 16y agoIsn't "upto" a loop? The idea, IIRC, is to print the numbers without loops and conditionals.
- 3pt14159 16y ago1.upto(10).class => Enumerator
- jerf 16y agoIt "can be" implemented recursively. If you're going to be pedantic about this (and who doesn't love being pedantic?) you need to be very careful about your definitions, because regardless of what you write you're going to have jump instructions in the finally-executed machine code. If you say that you can't have a loop "anywhere", you're limited to recursion, and then what will you do when someone comes along and points out that recursion and looping are ultimately equivalent? This is one of those cases where examining the boundary too closely makes it dissolve under the scrutiny, and it's better just to smile and nod and play along (and have fun arguing).
- imechura 16y agoprintf("1 To 1000");
- deleted 16y ago[deleted]
- lysium 16y agoHow is 'goto repeat' not a loop? You've just 'spelled out' a for-loop, I think. :-)
- tspiteri 16y agoSorry for posting a comment and deleting it, but just after posting I saw repeat: ... goto repeat; which is an endless loop, even if it is not a for loop, and just deleted the comment. Evidently I did not delete fast enough.
- alf 16y agoIn your defense, a modern compiler will generate code very similar code from the code linked in the OP. Non-optimized recursion is very expensive in C :) http://stackoverflow.com/questions/34125/which-if-any-c-compilers-do-tail-recursion-optimization/34129#34129 http://stackoverflow.com/questions/34125/which-if-any-c-comp...
- lysium 16y agoThe original question is unclear. What is a 'loop' and what is a 'conditional'? Tail-recursive calls (like the linked solution uses, though C compilers usually do not implement 'proper' tail calls) or short-cut conditionals might not look like but are still loops or conditionals. So, why the answer is funny it does not answer the original question.
- seiji 16y agothough C compilers usually do not implement 'proper' tail calls With optimizations turned on, gcc turns a tail recursive function into the equivalent of a for loop.
- danvet 16y ago.. which I've lately found out the hard way: Code of mine randomly crashed and valgrind told me it's due to use of unintiliazed memory. An awful lot of time later (i.e. one valgrind --track-origins=yes run) I know that it's from function foo's stack space. Which contains one local variable which is clearly assigned at the beginning. _Much_ later I find out that the problem is in bar, tail-called by foo. At least now I know that latest gcc can do tail-call optimizations.
- deleted 16y ago[deleted]
- nova 16y agoNice. Linear interpolation of C functions.
- orblivion 16y agoI'd say: #include<stdio.h> void output(x) { int y; printf("%i\n", x); y = 1 / (1000 - x); output(x + 1); } int main() { output(1); } With gcc on Linux it has the added bonus of "Floating Point Exception", don't know if that disqualifies it. EDIT: Nevermind, I got it: #include<stdio.h> int output(x) { printf("%i\n", x); (x >= 1000 ) || output(x + 1); return 1; } int main() { output(1); }
- blazer 16y agoThis might be from some clever and lazy programmer.. lol 291 printf("numbers from 1 to 1000");jondavidjohn Dec 31 '10 at 7:07
- blazer 16y agoWell, 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)
- amitraman1 16y agoMy favorite is: system("/usr/bin/seq 1000"); Only thing is, the interviewer would ask, "How would this work in Windows?"
- pbhjpbhj 16y ago>the interviewer would ask, "How would this work in Windows?" Cygwin?
- xenophanes 16y agotoo lazy to write it, but you could easily write a ruby script which writes a C program to a file. The ruby script loops to 1000. the C program is around 1000 lines long, prints one number per line. the ruby script compiles and runs the c script. problem solved?
- vilya 16y agoJust because I haven't seen it mentioned yet, here's a solution using gcc's computed goto feature: #include <cstdio> int main(int argc, char** argv) { void* labels[2] = { &&doing, &&done }; int i = 1; doing: printf("%d\n", i++); goto *labels[i / 1001]; done: return 0; } Still consider goto harmful? (Well yeah, so do I generally. But hey...)
- mhb 16y agoprintf("1 10 11 100 101 110 111 1000");
- swah 16y agoBad HN title.
- Almaviva 16y agoWriting "a + condition * (b - a)" is just a math cheat to make a ternary operator. So isn't this a conditional itself?
- wbhart 16y agoWow, HN must have a pretty large readership. Note that before this got posted on HN today my SO score from the solution was pretty static, for weeks. All of a sudden it's sprung up 300 points. If I learned one thing from the experience it is that often the popularity of something is not a measure of how "correct" it is. It's often a measure of the compromises you are prepared to make, and also how "appealing" it is. FWIW, thanks HN. I actually read about the question right here in the first place! By the way, the "correct" version was added by someone else. Posts to whoever added it.
- deleted 16y ago[deleted]
- KeithMajhor 16y agoUsing the preprocessor http://pastebin.com/Gxia1aBV http://pastebin.com/Gxia1aBV
- singular 16y agoIt's things like this which convince me that I am never going to pass an interview at a decent tech place. When I attempt to write solutions to things like this I make a million mistakes and can never quite get there. My idea was to create a buffer of 1000 bytes and recursively call a function while each byte is dereferenced until it finally hits a byte which causes a segfault... but I just can't get it working. The function pointer solution is genius...
- deleted 16y ago[deleted]