Hi there! This is my first posting. I'm new to C++ as well. I've included the code I've written for a simple factorial program. The program should only accept the numbers 1 - 8, and terminate when the user enters a value of zero. I've got everything up and running, but I can't figure out why this program will only return a value of '1' upon execution. I had this thing running earlier today. I can't figure out what I switched around that's throwing a wrench into the works. Any help would be greatly appreciated.
#include <iostream>
#include <cmath>
using namespace std;
int factorial(int);
int main()
{
int num = 1;
cout << endl;
cout << "This program will compute the factorial of a number (!n)\n";
cout << endl;
while((num != 0)&&(num <= 8)&&(num >= 1))
{
cout << "Enter a positive integer between 1 and 8 in order to view its factorial.\n"
<< "To terminate the program enter a value of zero.\n";
cout << endl;
cout << "Your integer: ";
cin >> num;
if ((num <= 0)||(num > 8))
{
cout << "Goodbye.\n";
}
else
{
cout << num << "! = " << factorial(num) << endl;
}
cout << endl;
}
return 0;
}
//function
int factorial(int num)
{
int result;
if (num >= 1)
return 1;
result = num * factorial(num - 1);
return result;
}
if (num >= 1)
That means if you parse an argument of num that is bigger than 1, the function will automatically return 1, hence why you get a result of 1. You should remove and change to if (num <= 1)
P.S. Wrap your code in [c0de][/c0de] tags please (code).