Friday, July 31, 2009

In C# how do I search an array to see if it already contains a particular number?

The user enters a number. I have have to search through the array to see if it already contains this number. If it does, then it will be disregarded so that their are only unique numbers in the array. If the number is not already in the array, it will add it to the array.





I have the array already denifined by the number that the user inputs, I just do not know how to search the array to see if that number is there or not. I was using if statements to compare the number to each element of the array, but that would get rid of both copies of the number instead of keeping one. Please help!

In C# how do I search an array to see if it already contains a particular number?
With Array.IndexOf you can easily check the existence of an element without using predicates. Use the following code as a guideline:





type[] myArray = whatever;





if (Array.IndexOf(myArray, theNumber) != -1)


{


// The number already exists in the array


}


else


{


// The number does not exist in the array


}
Reply:I don't know C#, but here's pseudocode:





boolean isInArray(int array[], int number)


{


for (x=0; x%26lt;=array.length;x++)


{


if (array[x] == number)


return true;


}


return false;


}





Then call that method in another function to put the number in or not depending on if it's true or not. You would also want to use a Vector (i'm not sure about C#'s array abilities but arrays are typically static meaning you can't add more elements after it's declared) so you can dynamically add more elements for as long as the person inputs numbers. Vectors work roughly the same way as arrays, but the number of elements can be dynamically changed. That and the vectors will have their own methods (at least they do in Java which C# imitates).

floral centerpieces

No comments:

Post a Comment