I'm new to the site today and need a little help with some homework. I am by no means looking for anyone to give me the answers, just to point me in the right direction. With that said I'm trying to write a function to calculate the factorial of a number using a FOR loop and it keeps giving me an answer of 0. Can someone please tell me what I'm doing wrong.
while ( yesno == 'y')
{
cout << " Please enter a number: ";
cin >> num;
cout << " The Factorial of " << num << " is " << answer << "\n\n";
do {
cout << " Would you like to enter another number?(answer y or n) ";
cin >> yesno;
cout << "\n";
} while ( yesno != 'y' && yesno != 'n');
}
system("pause");
return 0;
}
I understand what you are trying to do with your factorial function but it is a really odd/not ideal way to write the for loop...
you also need to add {} so that the for loop executes until it is satisfied and then after that returns answer. Ass you currently have it set it just returns answer without executing the for loop fully.
Also your do while loop where you ask if the user wants to add another input does not work correctly. Take a look at the logic behind your while statement and rework that part.
I went ahead and declared "i" outside the for loop. Is this considered more ideal?
Also added the {} to the for loop. it now allows for greater integers, before it wouldnt' calculate large numbers.
Looked at logic in the do while loop. Any hints behind the logic there? I did the extra space on purpose if that's what you're referring to? I just like the spaces between lines.
I was messing around with your code and made some asthetic changes that messed with the logic of the while loop, it was an error on my end, not yours. I ran the code and it works great. I wouldn't worry about it. In regards to the for loop I just don't like using num-- in that instance. It serves a dual purpose for you but it is easy to mess up IMHO. I would have made it more like: