Hello newguy17,
Here is an idea trying to work with what you have done:
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
|
constexpr std::size_t MAXSIZE{ 10 };
int a[MAXSIZE] = { 2,2,3,3 };
std::size_t index{ 4 }; // <--- Because you start with 4 elements used in the array and element 4 is next.
bool exist{ false };
do
{
for (i = 0; i < index; i++) // <--- Only checks the part of the array used.
{
if (add == a[i] && !exist)
{
std::cout << "Element already exist, choose another integer : " << std::endl;
exist = true; // <--- Defined as a bool.
}
}
if (exist)
{
std::cout << "\nEnter another number that is not " << add << ": ";
std::cin >> add;
exist = false;
}
else
break;
} while (!exist);
if (index < MAXSIZE)
a[index++] = add;
else
std::cout << "Error message for exceeding the size of the array. Your choice." << std::endl;
|
Lines 1 - 4 I normally put at the beginning of a function so I know where to find them.
Line 2 is here more for reference.
Line 3 I added and defines "index" with a value of 4 because 4 is the next element of the array to store something.
Line 4 I added to use in the do/while loop.
The do/while loop continues until you enter a number that does not already exist.
The for loop will check each element of the part array that is used .
The if statement will only print the message once even if there is more than one match.
The second if statement allows you to enter a new number if the first number exists in the array. Setting "exist" back to false allows the do while loop to check the new number.
The else statement is reached when "add" does not match anything in the array.
I started with just line 29 then added the if/else to make sure "index" does not go past the end of the array. The use of line 29 is to add after the used portion of the array and then add 1 to "index" before printing out the new array and ending the program.
A do while loop around most of your code would allow you to add more than one element to the array. This is an idea of what I usually do in this case:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
|
#include <iostream>
#include <cctype> // <--- For the touppet, tolower and others.
int main()
{
char choice{};
bool cont{ true };
do
{
// Your code here.
std::cout << "\n Do another Y/N: ";
std::cin >> choice;
choice = std::toupper(choice);
if (choice != 'Y')
cont = false;
} while (cont);
}
|
All this can be added to what you already have.
Hope that helps,
Andy