JaGood
JaGood

Reputation: 21

While loop error: "Uninitialized local variable used"

I'm doing an assignment where I modify a program that calculates the factorial of numbers so that the program terminates when the user enters the number '0'. Here is the code:

#include <iomanip>
#include <iostream>
using namespace std;

int main()
{
    unsigned int numb;
    unsigned long fact = 1;

    while (numb > 0)
    {


        cout << "Enter a number: ";
        cin >> numb;

        for (int j = numb; j > 0; j--)
        {
            fact *= j;
            cout << "Factorial is " << fact << endl;

        }
    }

    return 0;
}

However, I keep getting getting this error message:

error C4700: uninitialized local variable 'numb' used

What am I doing wrong?

Upvotes: 0

Views: 1575

Answers (3)

21koizyd
21koizyd

Reputation: 2003

If you want make factorial so must make like this (in your variables): 1. Give number 2. Loop with reduced counter( --j) 3. Multiply by counter in loop. 4. After loop, display result (fact).

#include <iostream>
using namespace std;

int main()
{
    unsigned int numb;
    unsigned long fact = 1;
    cout << "Enter a number: ";
    cin >> numb;
    for (int j = numb; j > 0; --j)
    {
        fact *= j;
    }
    cout << "Factorial is " << fact << endl;
    return 0;
}

Upvotes: 0

R.Coleman
R.Coleman

Reputation: 1

I'd put a

cout << "Enter a number: ";

cin >> numb;

before the while loop to initialize numb before entering. Then move the existing cout, cin statements to the end of the loop.

Upvotes: 0

David Schwartz
David Schwartz

Reputation: 182763

unsigned int numb;
unsigned long fact = 1;

while (numb > 0)

When you first hit this expression, what is the value of numb? The compiler doesn't know either.

Upvotes: 1

Related Questions