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!