#WSQ06

Long time no see you, guys. This is a blog post for the WSQ06, which is a factorial calculator. The tricky part is to write down the function, to understand the logic of the factorial numbers to teach it to the computer. I used a “unsigned long long” because when you get the factorial of a big number things get pretty nasty for an int. And in the end, you just need to write a loop in case the user wants to run the program again (which we’ve already done dozens of times).

Code:

#include <iostream>
using namespace std;
unsigned long long factorial(int n)
{
unsigned long long result;
if(n>0)
result=n*factorial(n-1);
else if(n==0)
result=1;
return result;
}
main ()
{
unsigned long long num, res;
char op;
do{
cout<<“Write the number you want to convert:”<<endl;
cin>>num;
res = factorial(num);
if(res==0)
cout<<“You cannot get factorials from negative numbers.”<<endl;
else{
cout<<“The factorial number is: “<<res<<“.”<<endl;
}
cout<<“Do you want to calculate another number? (y/n) “;
cin>>op;
if(op==’N’||op==’n’)
cout<<“Have a nice day!”<<endl;
else
cout<<“Let’s go again!”<<endl;
}
while(op==’Y’||op==’y’);
return 0;
}

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s