vladponcea
vladponcea

Reputation: 35

Returning a big number in for loop

I was working on a problem and got stuck into this silly error and I can't solve it. Basically I am using a for loop and reading a character from stream. When the character is '-' I am decreasing my integer by one and when it is '+' I am increasing it by one. I used an unsigned int because I don't want negative numbers. Here is an example of code:

char x;
unsigned int number = 0;
for (int i = 0; i < n; i++){
    cin >> x;
    if (x == '-'){
        number--;
    }else if (x == '+'){
        number++;
    }
}
cout << number;

And it shows a number something like this 4294967293.

Where is the problem?

Upvotes: 0

Views: 178

Answers (2)

BishalG
BishalG

Reputation: 1424

If your problem statement says that final resultant number will not be negative, it does not mean that the intermediate numbers will also be positive only. Because, there can be a sequence of streams with characters like - + + which leads to values like: 0, -1, 0, 1. Here, final answer is positive but intermediate numbers are still negative.

Now, you are trying to hold both positive and negative numbers in unsigned int datatype which is leads to wrong output here in above example. Because, if number is 0 and you try to apply negation, it will be 4294967295 (maximum value for a variable of type unsigned int) instead of being -1.

So, instead of using unsigned int datatype , you can use int datatype as suggested by Kaidul.

Upvotes: 2

Kaidul
Kaidul

Reputation: 15855

This is due to wrapping around of unsigned data type. Since it's unsigned, it can't be negative. So negation operation wraps around and yields boundary values of 32 bit integer.

Replace

unsigned int number = 0;

with

int number = 0;

Upvotes: 2

Related Questions