Code: #include<iostream> #include<conio.h> using namespace std; int fac(int n) { return n*fac(n-1); } int main() { fac(3); } running the following program in bloodshed dev C++, the output just flashes for a milisecond . tried getch() and all other possible stuff.
#include<iostream> #include<conio.h> using namespace std; int fac(int n) { int c; c = n*fac(n-1); cout<<c; } int main() { fac(3); } tried this also ! tried with getch( ) also !
If you open a DOS box in the directory containing the executable and run the executable from the command line then you will see the output. The problem is that when you run a DOS application in Windows, as soon as the executable finishes, Windows closes the DOS box so you don't get to see the output. Visual Studio sort of acknowledges this by adding code to prompt for a keypress after your main function has returned, so that's what you'll need to do, and that's what shabbir's on about when he mentions getch().
right, dats y i said in my previous message that i tried getch( ) in main( ) , sorry for not mentioning it in the code. I wish if u cud rewrite the code for me so that i cud figure out the problem whether it is in the code or with the compiler.
for any recursion function, termination condition should be. your code should be like.. Code: #include<iostream> #include<conio.h> using namespace std; int fac(int n) { int c; if(n<=1) return 1; else return(n*fac(n-1)); } int main() { int factVal=0; factVal = fac(3); cout<<"Fatorial of 3 is "<<factVal<<endl; getch(); return 0; }
Ah, It was more a logical error ! I should have considered that i was dealing with recursion. thanks. wipe out the variable c in your code. the correct code close to my earlier one should be like this : /* Code: #include<iostream> #include<conio.h> using namespace std; int fac(int n) { int c; if(n<=1) return 1; else return c = n*fac(n-1); } int main() { cout<<fac(4); getch(); } */