Do while loop!

So here is the code for finding average of student's marks and find average if the user enters -1 but I am not getting why we have to add 1 in total and then subtract 1 from i .

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>
using namespace std;
int main()
{
	int x,avg;
	int total = 0;
	int i = 0;
	do
	{
			cout << "Enter marks: ";
			cin >> x;
				i++;
				total = total + x;
	}
	while (x != -1);
		avg = (total + 1 ) / (i-1);
		cout << avg << endl;
	system("pause");
}

Notice that the while statement stops when x has -1. We don't want -1 to be part of the total or average, we just used -1 to stop taking input.

So by writing total+1 we eliminate the -1 we had added earlier. And we also decrement the i variable by 1 because we didn't consider the x=-1 as an input. ;)
Thanks bro!
Please mark as solved
Topic archived. No new replies allowed.