How to check if an int array contains a number

How can I check if an array contains a number? Here’s an example:

int [] array = new int [200];
array[0] = int(random(0,200));
If(array.contains 20){
println(“20”);
}

2 Likes

Look through the Processing resources:
https://processing.org/
https://processing.org/reference/
https://processing.org/tutorials/arrays/
https://processing.org/reference/Array.html
https://processing.org/reference/for.html
https://processing.org/reference/if.html

This is for a simple array…

At present the first two lines are assigning a random number to the first element array[0] of the array.

Once you start to understand arrays and work with them then:

  • add a few line of code to loop through the array and display contents
  • in the loop check to see if it contains the number.
  • use println() statements strategically to assist with understanding code

Once you can work through this and have a working example there are more advanced ways to do this.

:)

2 Likes

Nice question. So what we have to do here, is to go through all the numbers of the array, and check each one to see if they are equal to 20. We can do this with a loop.

for (int a = 0; a < ARRAY_SIZE; ++a)
{
   if (array[a] == 20)
      println("20");
}

So to visualize it:

array = { 7, 13, 20, 2 };

is the first element equal to 20?
if no, then is the second element equal to 20?
we keep doing this until an element hits 20

Hope this helps!

1 Like

For a primitive arrays you must loop through all the values and return true if they are equal.

boolean contains(int[] arr, int val) {
  for(int i=0; i<arr.length; i++) {
    if(arr[i]==val) {
      return true;
    }
  }
  return false;
}

However, for Object arrays you can use “.contains()” or a related method. Your example is a list of ints, and Processing already has this built-in: IntList.hasValue()

https://processing.org/reference/IntList_hasValue_.html

If you are working with Strings or floats there is StringList and FloatList. For other objects there is ArrayList, et cetera.

1 Like