The goal of my program is to have the user input sales from a given day and the number of iterations is unknown. How do I make the program stop inputting values into the array if the user enters -1? Also, the program is supposed to validate if the amount entered is positive and produce the max sale, minimum sale, and average sale.
Wait a sec, where in your requirements does it say you need an array? Nothing in your actual description seems to imply you need an array.
What you need are four important variables:
1. a variable to save the current sum 2. a variable to save the number of items entered so far (just the count) 3. a variable to save the minimum number entered so far 4. a variable to save the maximum number entered so far
In other words, I don't think you need an array or vector (or other container) to solve this.
I declared sales as an int, but the size is unknown because the user determines the number of times they enter a sale. Also, I know I don't have to use arrays, but it's required for the assignment. @Ganado
So... what does "use" mean in this instance? Can you declare an array but just not use it? Does that meet the requirements? Or do you have to store elements in it?
Are you allowed to dynamically allocate array sizes?
Three options:
1. Don't use arrays at all (it's really unneeded)
2. Use std::vector (it's basically an array with a nice wrapper)
3. Use dynamic arrays that you have to manually resize, since you don't know how many elements the user will input
I need to use an array and store the user inputs insides and when the user types -1 the program stops inputting numbers into the array. Then it proceeds to output the max, min and mean.
// Example program
#include <iostream>
// Assumptions: arr is either a nullptr and old_size is 0,
// or arr has previously been dynamically allocated using new[]
void add_to_array(int value, int*& arr, int old_size)
{
int* new_arr = newint[old_size + 1];
for (int i = 0; i < old_size; i++)
{
new_arr[i] = arr[i];
}
new_arr[old_size] = value;
delete[] arr;
arr = new_arr;
}
int main()
{
/// I need to use an array and store the user inputs insides
/// and when the user types -1 the program stops inputting numbers into the array.
/// Then it proceeds to output the max, min and mean.
int* arr = nullptr;
int size = 0;
while (true)
{
int value;
std::cout << "Enter value: ";
std::cin >> value;
if (value == -1)
break;
add_to_array(value, arr, size++);
}
std::cout << "out of loop\n\n";
std::cout << "Do more stuff here\n\n";
for (int i = 0; i < size; i++)
{
std::cout << arr[i] << '\n';
}
delete[] arr;
}
Enter value: 3
Enter value: 3
Enter value: 4
Enter value: 4
Enter value: 5
Enter value: 5
Enter value: 6
Enter value: 6
Enter value: 6
Enter value: 7
Enter value: -1
out of loop
Do more stuff here
3
3
4
4
5
5
6
6
6
7
constint capacity = a_big_enough_number;
double numbers[capacity];
int size = 0;
while(size < capacity and std::cin >> value and value not_eq -1)
numbers[size++] = value;