I just wrote a simple code.Since it have no warnings or error attentions from the VC compiler,it TOTALLY doesn't work!
What I wonder is whether the problem is due to the sequence of complying as well as how to figure it out.

------------------
Here is the code

#include<iostream>
using namespace std;
int fac(int n);
void main()
	{
	int m;
	cout<<"Enter a number:\n";
	cin>>m;
	cout<<"\n"<<fac(m);
	}
int fac(int n)
	{
	while(n!=1)
		return n*fac(--n);
	return 1;
	
	}

Dani AI

Generated

As reported, the code compiles but misbehaves at run time. and were right that recursion needs a clear base case; ’s point about protecting against endless recursion is important too. Beyond those basics, two subtle problems explain silent failures: the function modifies the parameter inside the call while also using it in the same expression (this modifies and reads the same variable in one expression, which is undefined behavior), and the loop that immediately returns never actually iterates. Also prefer the standard int main() signature and validate input.

A concise, safer recursive implementation (avoids in-expression modification, checks negatives and 64-bit overflow risk):

#include <iostream>

unsigned long long factorial(int n) {
    if (n < 0) return 0;             // invalid input indicator
    if (n <= 1) return 1;            // base case
    return static_cast<unsigned long long>(n) * factorial(n - 1);
}

int main() {
    int m;
    if (!(std::cin >> m)) return 0;
    if (m < 0) return 0;
    if (m > 20) { std::cout << "may overflow 64-bit\n"; return 0; }
    std::cout << factorial(m) << '\n';
    return 0;
}

An iterative version avoids recursion depth and is often preferable for larger inputs:

unsigned long long factorial_iter(int n) {
    if (n < 0) return 0;
    unsigned long long r = 1;
    for (int i = 2; i <= n; ++i) r *= i;
    return r;
}

Notes and cautions: factorials grow quickly (20! = 2432902008176640000 fits in 64-bit; 21! does not), so check ranges or use big-integer libraries for larger results. Enable compiler warnings and static analysis to catch nonstandard main signatures and suspicious constructs. Avoid modifying a variable and reading it in the same expression — that is the most likely root cause of the “works in compiler, fails at runtime” behavior here.

Recommended Answers

All 4 Replies

You do not need a while loop in your function. Think about the steps you need to do to get a factorial. There should be a conditional statment in a secursive function to check if you have reached a base case. There should be a call to the function itself if you have not reached a base case. Generally you do not use a loop in a recursive function.

A recursive function needs to do several things. 1. It has to test to see if it is done (To see if it has reached a base case). 2. It has to call itself. 3. The data that the function looks at should be different for each iteration, otherwise, it will end up in an endless loop. 4. It is a good idea to have some sort of protection to make sure it doesn’t end up in an endless loop.

Take a look at this thread:
http://www.daniweb.com/software-development/cpp/threads/411352

you dont need this line I think.

while(n!=1)

before executing this line you need an if statement

return n*fac(--n);

if n == 0 or 1, return 1,
else

return n*fac(--n);

Having learning related konwledge about recursion ,I come to get aware of how to solve such questions .
Sincerely thanks to those who give me hints in time.

------tiredoy

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.