Hey guys, now I have an assignment to create code that will ask for a number and then calculate the factorial of it with a for loop in a separate function and return the value to main..

Here is my code, I think it looks pretty good, but when I run it it just sends me the black box and it just stays blank with the blinking _ so Im not sure if it is trying to run it or something else is going on.

#include <iostream>

using namespace std;

double factorial(double num); //factorial prototype

void main ()
	int num;
	int answer;
	answer= factorial(num);
	cout << "Please enter a number: ";
	cin >> num;
	if (num < 0)
			cout <<"Please enter a positive integer.\n";
			cout <<"Factorial of " << num << " is: " <<answer;
	cout << "\n\n";

system ("pause");

//compute factorial 
double factorial (double num)
	double answer;
	int n;
	for (n = 1; n <= num; n++)
		num *= n;
	return answer;

Recommended Answers

All 2 Replies

First, you are calling the factorial function before taking the input from user i.e. num is not initialized.

Secondly, the loop inside factorial function is infinite. It is supposed to run from 1 to num, but watch carefully you are multiplying num inside it so it'll keep on increasing and the loop will go on forever. Also, you are returning answer which has never been initialized.

The art of programming starts when you carefully crafted code doesn't work. That is when you start trying to make your code do something, (anything), to help you understand it. Yours is a classic case.

The first thing to do is add a print statement std::cout<<"I am here"<<std::endl; . The first place to try is straight after int main() { .

Second turn on the compiler warnings, and fix 100% of them. For example it is int main() not void.

Thirdly, start printing out every variable, and figure out if you believe the value you are seeing.

Finally, on most systems you are going to get away with it, but std::cout is buffered and the buffer is flushed with the command std::cout.flush(); However, that is a lot of hassle to write after every output, so we have the stream modifier std::endl which does two things: (a) adds a line-feed (return) which is appropriate for the system, and second flushed the output. That means that it doesn't wait till the end of the program or the buffer becoming overly full to output the text to the screen or file. In this case, were the program is hanging that might be something to think about.

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.