Look at this program compiled using Turbo c++ 3.0 compiler
Aim is to calculate the factorial of a no.

#include<iostream.h>
#include<conio.h>
long double factorial(int);

void main() //main function
{
int inp;
clrscr();
cout<<"Enter a positive no. ";
cin>>inp;
cout<<"factorial is :"<<factorial(inp);//displays factorial
getch();
}

long double factorial(int a)
{
long double fact=1;
while(!a==0)
	{
	fact=a*fact;
	--a;
	}
return fact;
}

But when it runs it gives unexpected result, it can't find the factorial of no. grater than six.

Can you correct this program and explain why it is wrong without altering it's simplicity.....

Remember this program is from a beginner level program so, only correct it , don't use complex methods.

Recommended Answers

All 6 Replies

compiled using Turbo c++ 3.0 compiler

Have you considered dropping that ancient piece of shit and switching to a compiler that isn't twenty years old and severely limited under modern architectures?

it can't find the factorial of no. grater than six

If this were true I would be confused, but your algorithm is correct and works for values of N greater than six. However, factorials grow at an insane rate, and despite using long double to counteract that growth, you're still going to exceed limits (thus invoking undefined behavior) very quickly.

If you want arbitrarily large factorials, you need some kind of big number library such as GMP.

I have to use Turbo C++ due to our school syllabus.

And isn't any other method for doing this like use of arrays etc. without using no. lib.?

Thanks!

I have to use Turbo C++ due to our school syllabus.

I don't care. If you have to use it, you have to use it, but people are still going to complain that you're learning how to use an environment that's utterly useless outside of your school.

And isn't any other method for doing this like use of arrays etc. without using no. lib.?

You specifically rejected complex methods. Use of arrays constitutes duplicating the effort of an arbitrary length math library, which falls under "complex methods" far more than using a library in the first place. You can certainly implement your own big number class, but it's not trivial.

Does your teacher know we live in century XXI?
I guess he is probably too lazy to write a new syllabus:(

I also tried your program in Turbo C++. It worked and giving the result as expected.
I can understand your problem of using turbo c++ as I myself has undergone through such condition.

Also, I would suggest you to write int main() rather than void main() because the latter is deprecated and modern compilers even reject void main()

It works correctly.himgar is right.

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.