loop help

Hey guys, so Im trying to write a program that takes the average of up to 15 numbers and find the average. Ive been able to get the loop that finds the average to work. But when i try and have it so a keyword will exit the loop and find the average early. I run into real problems. Please Help!

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
33
34
35
36
37
38
39
40
#include "stdafx.h"
#include <iostream>
#include <string>
#include <stdlib.h> 
using namespace std;

int main()
{
	int i = 0;
	int total = 0;
	const int sizeofarray = 15;
	float numbers[sizeofarray];
	string end = "";


	cout << "Please enter up to 15 numbers" << endl;
	cout << "You can stop at anytime by typing 'done'" << endl;
	cout << "Please enter a number: ";

	for (int i = 0; i < sizeofarray; i++) {
		cout << "Please enter another number, or say done: ";
		cin >> end[i];
		total += numbers[i];

		while (end != "done" || i < 15) {
			cout << "while loop enter number: ";
			cin >> end[i];

			if (end != "done") {
				numbers[i] = atoi(end.c_str());
			}
			else {
				cout << "The average is " << (float)total / sizeofarray << endl;
				return 0;
			}
		}
		cout << "The average is " << (float)total / sizeofarray << endl;
	}
	return 0;
}
line 22,27: You don't want a subscript here. std::string overloads the [] operator so this refers to the 1st, then the 2nd, then the 3rd, etc. character of the string as i increments.

line 25: You have the wrong operator here. You want &&, not ||. With ||, if end == "done" and i is < 15, your loop will continue.

Line 33,37: If you enter "done" early, your average is going to be wrong since you are dividing by 15, not the number of entries in the array.
Thank you!!! For lines 33 & 37 would dividing by 'i' fix that problem?
Last edited on
Ok, I just found out that it dosnt. but Im not sure why that dosnt work. Because isnt 'i' keeping track of how many numbers have been entered? or am I just way of
That would fix it at line 33, but not line 37.

At line 37, i has gone out of scope, so you don't know how many values were actually entered.

I would replace lines 33-34 with a break statement to end the loop, but you're still going to have to keep a separate counter.

It's also not necessary that numbers be an array unless that was a requirement of your assignment. Once you've added the number to the total, you're done with it.
Im not sure what you mean 'i has gone out of scope' my understanding is that 'i' is keeping track of how many numbers are in the array.

Also thank you for your help! This has become much clearer to me!
I'm not sure what you mean 'i has gone out of scope'

i is defined at line 20. It is a local variable that exists only within the scope of the for loop. At line 36, the for loop ends and i goes out of scope.

If you were to attempt to use i at line 37, the compiler would tell you that i is undefined.
Topic archived. No new replies allowed.