Binary
Binary

Reputation: 57

While loop task in c++

I am a beginner in c++ and I am having problems with making this code work the way I want it to. The task is to write a program that multiplies all the natural numbers up to the loaded number n.

To make it print the correct result, I divided x by n (see code below). How can I make it print x and not have to divide it by n to get the correct answer?

#include<iostream>
using namespace std;
int main(){
    int n,x=1;
    int i=0;
    cout<<"Enter a number bigger than 0:"<<endl;
    cin>>n;
    while(i<n){
        i++;
        x=i*x;  
    };
    cout<<"The result is: "<<x/n<<endl;
    return 0;
}

Upvotes: 2

Views: 496

Answers (3)

R Sahu
R Sahu

Reputation: 206747

How can I make it so that in the last cout I can only put x and not have to divide x by n to get the correct answer?

It will be better to use a for loop.

// This stops when i reaches n. 
// That means, n is not multiplied to the result when the loop breaks.
for (int i = 1; i < n; ++i )
{
   x *= i;
}

cout << "The result is: " << x <<endl;

Upvotes: 1

Sirmyself
Sirmyself

Reputation: 1564

You already have two very good options, but here is an other one you might want to take a look at when you are at ease enough in programming :

unsigned factorial(unsigned value)
{
    if (value <= 1) 
    {
        return 1;
    }
    else
    {
        return value * factorial(value - 1);
    }
}

It's a recursive function, which is kind of neat when used in proper moments (which could not be the case here unfortunately because the execution stack might get so big you fill your memory before you're done. But you can check it out to learn more about recursive functions)

When your memory is full, you then crash your app with what is called actually a stack overflow.

Upvotes: 2

Aconcagua
Aconcagua

Reputation: 25546

At very first a principle you best get used to as quickly as possible: Always check user input for correctness!

cin >> n;
if(cin && n > 0)
{
    // valid
}
else
{
    // appropriate error handling
}

Not sure, why do you need a while loop? A for loop sure is nicer in this case:

int x = 1;
for(int i = 2; i < n; ++i)
   x *= i;

If you still want the while loop: Start with i == 2 (1 is neutral anyway) and increment afterwards:

i = 2;
while(i < n)
{
    x *= i;
    ++i;
}

In case of n == 1, the loop (either variant) simply won't be entered and you are fine...

Upvotes: 5

Related Questions