-
what to use????
Hello..
Can array be used to store values input by the user if there is no specific number of values to store?
I have this program and I want to know what mistakes I did in the loop ( I know there are quite a few.. :) ) I tried to run it and it actually did except it hung after the prompting for the user values.
Code:
//This program asks the user to input the number of values to average
//and each of the values and then outputs the average
#include <iostream>
using namespace std;
int main ()
{
int n = 0, i = 0, avg = 0, num = 0;
cout << "Enter the number of values to average: ";
cin >> n;
while ( n > 0);
{
cout << "Enter value for" << i + 1 << " : ";
cin >> num;
n--;
}
avg = ( num + num )/n;
cout << "Average = " << avg << endl;
}
I have no clue why it hung....
Any ideas on what loop is best to use? For loops wouldn't work since there is no specific number of times for the looping, would it?
Thanks...
-
You do know how many times to loop.
Code:
for ( int it = 0; it < n; ++it )
-
Arrays are problematic. You'd have to give them some size, and no matter how big, the user might want to enter more than that.
So instead I recommend you use a std::vector. It's a class from the standard library that works like an array but can be extended.
Code:
#include <vector>
#include <iostream>
int main()
{
int n;
std::cout << "Enter the number of values: "
std::cin >> n;
std::vector<int> values;
values.reserve(n); // Reserve memory for n ints, so that later it doesn't need to reallocate.
for(int i = 0; i < n; ++i) {
int tmp;
std::cout << "Enter value #" << (i+1) << ": ";
std::cin >> tmp;
values.push_back(tmp); // Append tmp to the end of values, thus making it 1 larger.
}
}
Just keep in mind that reserve() doesn't actually change the size of the vector.
-
If you're familiar with arrays and want to use array syntax, you can just create the vector with the right number of elements. This works for vectors but not arrays because arrays can't be created with a size that isn't known until runtime (at least, not in standard C++).
Code:
#include <vector>
#include <iostream>
int main()
{
int n;
std::cout << "Enter the number of values: "
std::cin >> n;
std::vector<int> values(n);
for(int i = 0; i < n; ++i) {
std::cout << "Enter value #" << (i+1) << ": ";
std::cin >> values[i];
}
}