how to ignore the negative number that is used as a break for the for loop

Jun 27, 2019 at 7:38am
how to ignore the negative number that is used as a break for the for loop?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
 #include <iostream>
#include <string>
using namespace std;

int main()
{
	int score, total;
	for (int counter = 0; score > -1; counter++)
	{
		cout << "Please enter non-negative score:";
		cin >> score;
		
		if (score < 0) //this takes a negative number and use it as a break to stop the loop
		{
		    total = score + score; 
		    cout << "true total score is: " << total << endl;
			break;
		}
	}
	return 0;
}
Jun 27, 2019 at 7:55am
Like so?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
 #include <iostream>
#include <string>
using namespace std;

int main()
{
	int score = 0, total;  // need to initialise
	for (int counter = 0; score > -1; counter++)
	{
		cout << "Please enter non-negative score:";
		cin >> score;
		
		if (score < 0) //this takes a negative number and use it as a break to stop the loop
		    break;

		total = total + score;  // not score + score
	}
	cout << "true total score is: " << total << endl;
	return 0;
}

Jun 27, 2019 at 8:35am
@salmem_c yes, its working as intended now, thank you
Jun 29, 2019 at 1:25pm
Unless I'm missing some very obvious, variable total gets initialized to somewhere around 32764 by gcc.
score value is added to total in the loop.
Topic archived. No new replies allowed.