While loop help

Jun 4, 2020 at 2:51am
Would someone please help me understand why the following codes produce different outcomes for the variable sum when the variable number's type is changed to unsigned int. In addition, the second while loop doesn't terminate with a negative number. Thanks.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
  int number, sum = 0;
	
	while (cin >> number && number > 0)
		sum += number;
	cout << sum;


unsigned int number, sum = 0;
	
	while (cin >> number && number > 0)
		sum += number;
	cout << sum;


Jun 4, 2020 at 3:00am
the second while loop doesn't terminate with a negative number.

An unsigned int can NEVER be negative, it wraps around to a large positive number. Both of your while loops should end when 0 is entered.
Jun 4, 2020 at 3:23am
@Furry Guy

I understand that unsigned can't be negative and the wrap-around effect of int, but that doesn't explain the result when the the following input is entered.
1 2 3 -1 a. With this input, a terminates the loop rather than -1 and the sum is 6 rather than 5.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
int main()
{
	unsigned int number, sum = 0;

	cout << "Enter numbers: ";

	while (cin >> number && number > 0)
	{
		sum += number;
	}
	cout << sum;
	
	return 0;
}
Jun 4, 2020 at 3:38am
Both sum AND number wrap around when entering -1. std::cin goes into an error state when 'a' is entered, 'a' is not an integer so the comparison is invalid, and the loop terminates.
Topic archived. No new replies allowed.