
arrays
Hi there. I am learning and i have to have a program by sunday night. I am stuck. I have to input 20 numbers, if I put in a number that is already in the array then it ignores it. each input is stored to the next element in the array
i can make my array, and it will take inputs 20 times, what i cannot figure out is how to compare all elements to see if my input matches one of them.
Help

Use a loop the iterate through the array. Something along the lines of the following:
Code:
for ( int i = 0; i < LEN; i++ ) {
if ( array[i] == input )
flag = TRUE;
}
if ( flag == TRUE )
// Ignore
There are a number of ways to structure this.
Prelude

For each number you should check if it is already in the array. In pseudocode:
Code:
input_value = get_input_value ()
already_in_array = FALSE
for index = 0 to nr_of_input_values
if input_value = array [index]
then already_in_array = TRUE
If already_in_array is TRUE, then ignore the input value.
Note that nr_of_input_values is a variable and not a constant. If you have 5 elements in the array, it isn't very efficient to check 20 elements.
Perhaps the algorithm can be done in other (more efficient) ways, but this one is usable.

I understand what you are saying, but i cannot figure out how to get it to work... let me show you what i have right now.
#include <iostream.h>
const int MAX = 20;
int Count(int n, int Nbr[MAX])
{
cout << "Number " << n + 1 << ": ";
cin >> Nbr[n];
return Nbr[n];
}
int main()
{
int Number[MAX];
cout << "Please type 20 integers.\n";
for( int i = 0; i < MAX; i++ )
{
Count(i, Number);
}
return 0;
}

you can use a goto:
Code:
int Count(int n, int Nbr[MAX])
{
cout << "Number " << n + 1 << ": ";
e:
cin >> Nbr[n];
for (int i=0;i<n;i++)
if (Nbr[i]==Nbr[n]) {
cout << "That number has already been typed in" << endl; goto e;
}
return Nbr[n];
}
if you're finiky about gotos, then do it this way:
Code:
int Count(int n, int Nbr[MAX])
{
int flag_already_typed;
cout << "Number" << n+1 << ": ";
do {
flag_already_typed=0;
cin >> Nbr[n];
for (int i=0;i<n;i++)
if (Nbr[i]==Nbr[n]) {
cout << endl << "that.. blah blah blah .. " << endl; flag_already_typed=1;
}
} while (flag_already_typed);
return Nbr[n];
}
whenever possible, put [ code] and [/code] around your source code