1

I'm writing a program to calculate some values of an array of unknown size. I successfully made it so the user can input 5 numbers to be calculated. But I want the user to be able to enter them as a bunch of numbers on the same line and end with a 0. We don't know the size of the array. It would be possible to add a large number like 100 if it would get too complicated.

It should look as following:

Enter a couple of numbers : 10 12 -5 20 -2 15 0
Sum = 50
Average value = 8.3
Largest number = 20
Second largest = 15

This is my code at the moment:

#include<iostream>
#include<conio.h>
using namespace std;

// Variables

int size = 5;            //Array size
int sum = 0;
int a[5];

// Functions
int highest();
int secondh();

int avg(int, int);

//Main
int
main()
{
  cout << "Enter 5 numbers to calculate..." << endl;
  int x;

  for (x = 0; x < 5; x++)
    {
      cout << "insert value #" << x + 1 << endl;
      cin >> a[x];
      sum = sum + a[x];
    }

  // sum
  cout << "The sum is: " << sum << endl;
  // avg
  cout << "Average number is: " << avg (sum, size) << endl;
  // max
  cout << "Max value is: " << highest () << endl;
  // second max
  cout << "Second largest value is: " << secondh () << endl;
  getch();
  return 0;
}

//AVG
int
avg (int sum, int size)
{
  return sum / size;
}

// HIGHEST
int
highest ()
{
  int max = a[0];
  int min = a[0];
  int e = 0;

  while (e < 5)
    {
      if (a[e] > max)
    {
      max = a[e];
    }

      e++;
    }

  return max;
}

// SECOND HIGHEST
int
secondh()
{
  int max = a[0];
  int smax = a[0];
  int e = 0;

  while (e < 5)
    {
      if (a[e] > max)
    {
      smax = max;
      max = a[e];
    }
      e++;
    }
  return smax;
}

It's the Cin part im having issues with... Have no clue on how to extract the user input of a bunch of numbers into an array.

for (x = 0; x < 5; x++)
{
    cout << "insert value #" << x + 1 << endl;
    cin >> a[x];
    sum = sum + a[x];
}

To sum my issue: First of all, how to enter all the numbers in one line into an array and end with a zero? Second how use an unknown sized array? (Will use a large sized array if it gets to complicated (it's a manual input program.))

Thanks!

Synchro
  • 35,538
  • 15
  • 81
  • 104
MarkBear34
  • 29
  • 6
  • are you allowed to use `std::vector`? – bolov Jan 31 '15 at 14:19
  • So what's the question? – Walter Jan 31 '15 at 14:20
  • You seem to be in the right direction. You need to allocate a large enough array to fill your data, probably resizing it when needed. Regarding how to parse the input like, take a look at `strtok`. – h7r Jan 31 '15 at 14:21
  • @Walter as the he stated, "How to enter all the numbers in on line into an array and end with a zero." – h7r Jan 31 '15 at 14:22
  • @h7r `std::cin`'s `operator>>` tokenizes on whitespace characters, so using `strtok` seems not needed here. Am I right? – rubikonx9 Jan 31 '15 at 14:33
  • @g.tsh I double checked and you are fully right. Correct would be to `std::string foo; std::getline(std::cin, foo);` and THEN `std::strtok` over it. See http://stackoverflow.com/questions/289347/using-strtok-with-a-stdstring – h7r Jan 31 '15 at 14:41
  • @bolov Yes, vector is fine – MarkBear34 Jan 31 '15 at 14:57
  • @g.tsh, Something like that is exactly what im trying to accomplish! Was reading about getline after posting this. – MarkBear34 Jan 31 '15 at 14:59

3 Answers3

1

Don't use an array for that.

Standard C++ containers, such as std::vector or std::list, are the way to go in such a case. You can just append data to them without specifying the size of the container - it's handled automatically for you.

IF you do need to use arrays...

That would sound like an unreasonable homework (much more suitable for C, not C++). Anyway, in such a case, you'd have to facilitate dynamic memory management, and C's functions, such as malloc, realloc and free. In short:

  1. Create an array with some initial size N using malloc (or calloc).
  2. When you are to insert N-th number, use realloc to increase the array's size. Read this on proper use of realloc.
  3. When you're finished, free the memory allocated with free.

Regarding this: Will use a large sized array if it gets to complicated: not a good idea - what size do you think is large enough? 100 elements? 1000, 100000? You'll never know. It's not a manual input program - it's using data from standard input, and you can redirect pretty much anything there (ex. cat datafile | your_app).

Also, when calculating a sum, you'd like to watch out for an overflow / underflow.

Community
  • 1
  • 1
rubikonx9
  • 1,403
  • 15
  • 27
1

But I want the user to be able to enter them as a bunch of numbers on the same line and end with a 0

We can do that. We'll input them one at a time (and check to make sure the stream isn't terminated underneath us) and break if we get a zero:

std::vector<int> numbers;
for (int x; (cin >> x) && (x != 0); ) {
    numbers.push_back(x);
}

cin >> x will fail if the stream ends or if the user tries to enter a non-integer like Hello. So the body there is only executed if we succesfully input a non-zero x.

With that, you just need to change your functions to use a vector and rather than hardcoding 5 just rely on the size() method. For example, highest becomes:

int highest(const std::vector<int>& numbers)
{
    int largest = INT_MIN; // see <climits>

    for (size_t i = 0; i < numbers.size(); ++i) {
        if (numbers[i] > largest) largest = numbers[i];
    }
    return largest;
}

With the algorithms library, we can abridge that to something that is unnecessarily concise, but in the interest of completeness:

int highest(const std::vector<int>& numbers) {
    return std::accumulate(numbers.begin(),
                           numbers.end(),
                           INT_MIN,
                           std::max<int>);
}

(Note that with C++11, std::max<int> is itself overloaded, so you'd need to cast it to (const int& (*)(const int&, const int&))... )

Barry
  • 286,269
  • 29
  • 621
  • 977
  • Thanks, exactly what is was looking for! The cin worked great, but having some issues with passing the vector to the highest function. Im getting this error: `Compiling... red4.cpp Linking... red4.obj : error LNK2001: unresolved external symbol "int __cdecl highest(void)" (?highest@@YAHXZ) Debug/redo4.exe : fatal error LNK1120: 1 unresolved externals Error executing link.exe.` Am i missing any header files? `#include #include #include using namespace std;` – MarkBear34 Feb 06 '15 at 00:33
0

You don't need to store the numbers at all (though you could do that too using an expandable container), but merely keep track of the total number and sum so far, as well as the largest, smallest, and second largest etc...

For example, if you only want the average, you could

int main()
{
   std::cout<<" enter numbers, finishing with 0'<<std::endl;
   int c, num=0, sum=0;
   for(;;) {
     std::cin >> c;
     if(c==0) break;
     num++;
     sum+=c;
   }
   if(num)
     std::cout<<" average = " << double(sum)/double(num) << std::endl;
}

work out for yourself how to do maximum, minimum etc ... If you really need to keep the numbers in some container, you could

int main()
{
   std::cout << " enter numbers, finishing with 0' << std::endl;
   std::vector<int> numbers;
   for(;;) {
     int c;
     std::cin >> c;
     if(c==0) break;
     numbers.push_back(c);
   }
   if(numbers.size())
     std::cout << " average = "
               << std::accumulate(numbers.begin(),numbers.end(),0)/
                  double(numbers.size())
               << std::endl;
}
Walter
  • 44,150
  • 20
  • 113
  • 196