Is it not possible to recursion in the main function? Is the only alternative a loop? any help is appreciated.
Is it not possible to recursion in the main function? Is the only alternative a loop? any help is appreciated.
It's possible to use recursion on any function you want, including main().
If you understand what you're doing, you're not learning anything.
>Is it not possible to recursion in the main function?
Yes, a recursive main is not legal in C++. It's legal in C, but typically reserved for spectacularly awful code.
My best code is written with the delete key.
you can of course do thisI am really not sure why you would want to do this though. You can also kind of "call main" by using a system call to launch your program again, presumably with new parameters. This borders on being either far to clever for your own good, or having a really basic misunderstanding of what's going on.Code:int rmain(int argc, char *argv[]) { // recursive whatever goes here } int main(int argc, char *argv[]) {return rmain(argc,argv);}
ok thanks for the heads up. I just want the program tp restart, and I though using recursion to jump back to the beginning would work.
>I just want the program tp restart, and I though using recursion to jump back to the beginning would work.
Good recursion solves a similar, smaller problem each time. If you want to do the same thing over and over, use a loop.
My best code is written with the delete key.
Ok, and instead of starting another thread, may i ask somethingthat is different. I am used to using "getchar();" for waiting for input, but I have seen cin.get(); used. is cin.get any more (or less) proper to use then getchar()?
>is cin.get any more (or less) proper to use then getchar()?
cin.get is the "C++" way of doing things and getchar is the "C" way. If you otherwise use C++ iostreams then you would be wise to use cin.get instead of getchar. There can be subtle sync issues when mixing C and C++ I/O.
My best code is written with the delete key.
ok thanks.
Huh. Good to know!Originally Posted by Prelude
If you understand what you're doing, you're not learning anything.
I prefer to use the word "clever" instead of "awful", but you get the general idea.
It's preferable to use a loop instead of recursive functions for many reasons. One is the overhead associated with function calls. Another is that if you run the recursive loop many times (we're talking at least a few hundred), functions which use a lot of variables will slowly eat up a computer's stack space. There's also the overhead when you roll back up the stack, when you're done with the recursive loop.
Code:#include <stdio.h> void J(char*a){int f,i=0,c='1';for(;a[i]!='0';++i)if(i==81){ puts(a);return;}for(;c<='9';++c){for(f=0;f<9;++f)if(a[i-i%27+i%9 /3*3+f/3*9+f%3]==c||a[i%9+f*9]==c||a[i-i%9+f]==c)goto e;a[i]=c;J(a);a[i] ='0';e:;}}int main(int c,char**v){int t=0;if(c>1){for(;v[1][ t];++t);if(t==81){J(v[1]);return 0;}}puts("sudoku [0-9]{81}");return 1;}