Help using 'while' and 'for' loops

I've recently started learning programming at university and I've been asked to write a C++ program for the following problem:

"The program will keep asking the user to enter a pair of integers, start and finish, and will terminate whenever start>finish, or EOF or an invalid input is encountered. Every time a new pair of integers are read, the program will first calculate the subtotal and then add the subtotal to the total. Before the program terminates, it should display the accumulated total and the average of all the subtotals."

That seemed easy to me at first, but an example was added at the end showing how the subtotals should be calculated:

"start2+(start+1)2+(start+2)2+ ... +(finish-1)2+finish2

eg. If you enter 3 for start and 8 for finish, then the formula for the subtotal becomes:

32 + 42 + 52 + 62 + 72 + 82"



My first attempt seemed promising to begin with, but it isn't producing the expected output. I'm not too sure if my combination of while and for loops is appropriate for this task and lines 18 and 19 seem to be a problem because the total displayed at the end is far larger than it should be.

I've omitted attempts at working out the average until I've figured out the total. I'm not even sure where to start for working out the average.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#include <iostream>
using namespace std;

int main ()
{
	int start, finish, squared, total = 0, subtotal = 0;
	float average;
	
	cout << "Enter Start as integer: ";
	cin >> start;
	cout << "Enter Finish as integer: ";
	cin >> finish;
	
	while(start <= finish)
	{
		for(start; start <= finish; start++)
		{
			squared = start * start;//I'm thinking this line and the following line are the main problem
			subtotal = subtotal + squared;
		}
		total = total + subtotal;
		cout << "Enter Start as integer: ";
		cin >> start;
		cout << "Enter Finish as integer: ";
		cin >> finish;
	}

	cout << "TOTAL = " << total << endl;
	cout << "AVERAGE = "; //I've left this blank because I'm not entirely sure about the average just yet

	return 0;
}




Any help would be greatly appreciated.
I don't see any problem. 32+...+82 = 199. Could you be that you miscalculated what to expect?
By the way, there is a closed formula for 12+...+n2 = n*(n+1)*(2n+1)/6. Take a difference of two such sums and you'll get start2+...+finish2.

As for the average, it is going to be total/count. You could have count++ after line 19 or 25. It depends on what you want to average.
Last edited on
Topic archived. No new replies allowed.