Aug 30, 2013 at 7:30am UTC
Hi Everyone! Can you help me do this program because i am a beginner. =)
Here is the sample output:
Enter Number: 5
Solution:
5 x 4 x 3 x 2 x 1
Result is 120
Using WHILE LOOP CODE!!
TY IN ADVANCE TO THOSE WHO WILL HELP ME! :)
Aug 30, 2013 at 7:47am UTC
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
#include <iostream>
int main()
{
int number;
std::cout << "Enter Number" << std::endl;
std::cin >> number;
int product=1; // set to 1 since we're multiplying
while (number > 0)
{
product*=number // this multiplies the current product by number;
number--; // this subtracts number by 1;
}
std::cout << product << std::endl;
}
Last edited on Aug 30, 2013 at 7:47am UTC
Aug 30, 2013 at 8:08am UTC
you may call this overloaded function:
1 2 3 4 5
long int factorial(int x) {
if (x==0) return 0;
else if (x==1) return 1;
else return x * factorial(x-1);}
Last edited on Aug 30, 2013 at 8:09am UTC
Aug 30, 2013 at 8:19am UTC
that's a recursive function. not an overloaded one.
Aug 30, 2013 at 9:53am UTC
I stand corrected but what is more important is what it does and not what it is classified.
Aug 30, 2013 at 9:58am UTC
0! is 1
Also, what does your function do in this case?
int res = factorial(-3);
Andy
PS
http://en.wikipedia.org/wiki/Factorial
The value of 0! is 1, according to the convention for an empty product.
Last edited on Aug 30, 2013 at 9:59am UTC
Aug 30, 2013 at 10:14am UTC
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
#include <iostream>
#include <vector>
#include <numeric>
#include <iterator>
#include <functional>
int main()
{
while ( true )
{
std::cout << "Enter a non-negative number (0 - exit): " ;
unsigned int n = 0;
std::cin >> n;
if ( !n ) break ;
std::vector<unsigned int > v( n );
std::iota( v.begin(), v.end(), 1 );
std::cout << "\nTable of factorials for n = " << n << std::endl;
std::partial_sum( v.begin(), v.end(),
std::ostream_iterator<unsigned int >( std::cout, "\n" ),
std::multiplies<unsigned int >() );
std::cout << std::endl;
}
}
Last edited on Aug 30, 2013 at 2:41pm UTC
Aug 31, 2013 at 12:36am UTC
lol vlad. You're funny, and I approve.